Core PHP 11 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Create and call your own functions.
  • Pass parameters, use default values and return results.
  • Pass arguments by value and by reference.
  • Add type declarations and use PHP 8 named arguments.
  • Write recursive, anonymous (closure) and arrow functions.
Why Functions?

The real power of PHP comes from its functions. PHP has more than a thousand built-in functions (Part II). In addition, you can write your own.

To keep a block of code from being executed when the page loads, put it into a function. A function is executed only when it is called, and it can be called from anywhere in the page, as many times as you like. Functions make programs shorter, easier to read and easier to maintain.

Creating a PHP Function
Syntax
function functionName()
{
    code to be executed;
}

Function guidelines:

  • Give the function a name that reflects what it does.
  • The name can start with a letter or an underscore – not with a number.
  • Function names are not case-sensitive, but call them exactly as declared.

A simple function that writes a name when it is called:

File: htdocs/phpbook/ch10/func1.php
<html>
<body>
<?php
function writeName()
{
    echo "Rahul Sharma";
}
echo "My name is ";
writeName();
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch10/func1.php
My name is Rahul Sharma
Adding Parameters

To add more functionality to a function we can add parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses. The values passed when calling are called arguments.

The following example writes different first names with the same last name:

File: htdocs/phpbook/ch10/func2.php
<html>
<body>
<?php
function writeName($fname)
{
    echo $fname . " Sharma.<br>";
}
echo "My name is ";
writeName("Rahul");
echo "My sister's name is ";
writeName("Priya");
echo "My brother's name is ";
writeName("Amit");
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch10/func2.php
My name is Rahul Sharma.
My sister's name is Priya Sharma.
My brother's name is Amit Sharma.

The following function has two parameters:

File: htdocs/phpbook/ch10/func3.php
<html>
<body>
<?php
function writeName($fname, $punctuation)
{
    echo $fname . " Sharma" . $punctuation . "<br>";
}
echo "My name is ";
writeName("Rahul", ".");
echo "My sister's name is ";
writeName("Priya", "!");
echo "My brother's name is ";
writeName("Amit", "?");
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch10/func3.php
My name is Rahul Sharma.
My sister's name is Priya Sharma!
My brother's name is Amit Sharma?
Returning Values

To let a function return a value, use the return statement. return also ends the function immediately.

File: htdocs/phpbook/ch10/func4.php
<html>
<body>
<?php
function add($x, $y)
{
    $total = $x + $y;
    return $total;
}
echo "1 + 16 = " . add(1, 16);
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch10/func4.php
1 + 16 = 17

A function can return any type, including an array – useful for returning several values:

File: htdocs/phpbook/ch10/func5.php
<?php
function stats(array $nums)
{
    return [min($nums), max($nums), array_sum($nums) / count($nums)];
}
[$lo, $hi, $avg] = stats([12, 45, 7, 30]);
echo "Minimum: $lo, Maximum: $hi, Average: $avg";
?>
OUTPUT browser · http://localhost/phpbook/ch10/func5.php
Minimum: 7, Maximum: 45, Average: 23.5
Default Parameter Values

A parameter can have a default value, used when the caller omits the argument. Parameters with defaults must come after the required ones.

File: htdocs/phpbook/ch10/default.php
<?php
function greet($name, $greeting = "Namaste")
{
    return "$greeting, $name!<br>";
}
echo greet("Asha");
echo greet("John", "Hello");
?>
OUTPUT browser · http://localhost/phpbook/ch10/default.php
Namaste, Asha!
Hello, John!
Passing by Value and by Reference

By default arguments are passed by value: the function works on a copy, so changes inside it do not affect the caller's variable. Prefix the parameter with & to pass by reference – the function then works on the original variable.

File: htdocs/phpbook/ch10/reference.php
<?php
function addTenByValue($n) { $n += 10; }
function addTenByRef(&$n)  { $n += 10; }
$a = 5;
addTenByValue($a);
echo "After addTenByValue: $a<br>";
addTenByRef($a);
echo "After addTenByRef: $a";
?>
OUTPUT browser · http://localhost/phpbook/ch10/reference.php
After addTenByValue: 5
After addTenByRef: 15
Type Declarations and Named Arguments

Since PHP 7 you can declare the types of parameters and of the return value. PHP 8 adds union types (int|float) and named arguments, which let you pass arguments by parameter name in any order and skip optional ones.

File: htdocs/phpbook/ch10/types.php
<?php
declare(strict_types=1);

function area(float $length, float $width = 1.0): float
{
    return $length * $width;
}
function format(int|float $value, int $decimals = 2, string $prefix = ""): string
{
    return $prefix . number_format($value, $decimals);
}
echo "Area: " . area(4.5, 2) . "<br>";
echo format(1234.5) . "<br>";
echo format(1234.5, prefix: "Rs. ") . "<br>";          // named argument
echo format(decimals: 0, value: 98765.4);
?>
OUTPUT browser · http://localhost/phpbook/ch10/types.php
Area: 9
1,234.50
Rs. 1,234.50
98,765

With declare(strict_types=1); PHP refuses to convert values silently – calling area("4", 2) would throw a TypeError.

Variable-Length Argument Lists

The ... (splat) operator collects any number of arguments into an array:

File: htdocs/phpbook/ch10/variadic.php
<?php
function total(...$numbers)
{
    return array_sum($numbers);
}
echo "total(1, 2) = " . total(1, 2) . "<br>";
echo "total(5, 10, 15, 20) = " . total(5, 10, 15, 20) . "<br>";
$list = [3, 4, 5];
echo "total(...\$list) = " . total(...$list);
?>
OUTPUT browser · http://localhost/phpbook/ch10/variadic.php
total(1, 2) = 3
total(5, 10, 15, 20) = 50
total(...$list) = 12
Recursive Functions

A function that calls itself is recursive. Every recursive function needs a base case that stops the recursion.

File: htdocs/phpbook/ch10/recursion.php
<?php
function factorial(int $n): int
{
    if ($n <= 1) {
        return 1;               // base case
    }
    return $n * factorial($n - 1);
}
for ($i = 1; $i <= 6; $i++) {
    echo "$i! = " . factorial($i) . "<br>";
}
?>
OUTPUT browser · http://localhost/phpbook/ch10/recursion.php
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
Anonymous Functions and Arrow Functions

An anonymous function (closure) has no name; it can be stored in a variable or passed to another function. The use keyword imports variables from the surrounding scope. Arrow functions (fn, PHP 7.4) are short closures that automatically capture outer variables.

File: htdocs/phpbook/ch10/closures.php
<?php
$square = function ($x) { return $x * $x; };
echo "square(6) = " . $square(6) . "<br>";

$rate = 18;
$withGst = function ($price) use ($rate) {
    return $price + $price * $rate / 100;
};
echo "500 with GST = " . $withGst(500) . "<br>";

$prices = [100, 250, 400];
$discounted = array_map(fn($p) => $p * 0.9, $prices);
echo "After 10% discount: " . implode(", ", $discounted) . "<br>";

$func = "strtoupper";                 // variable function
echo "Variable function: " . $func("php");
?>
OUTPUT browser · http://localhost/phpbook/ch10/closures.php
square(6) = 36
500 with GST = 590
After 10% discount: 90, 225, 360
Variable function: PHP
Key Takeaways
  • Define functions with function name($params) { … }; call them by name.
  • Parameters receive arguments; return sends back a value and ends the function.
  • Default values make parameters optional; & passes by reference.
  • Type declarations (int, float|int, : string) and strict_types make code safer.
  • PHP 8 named arguments: format(1234.5, prefix: "Rs. ").
  • ... collects variable arguments; recursion needs a base case; closures and fn create functions on the fly.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch10 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : A named block of code that performs a specific task and runs only when it is called. Functions avoid repeating code and make programs modular.

Answer : function functionName($param1, $param2) { statements; return value; }

Answer : The name must start with a letter or underscore, may contain letters, digits and underscores, should describe what the function does, and is not case-sensitive.

Answer : A parameter is the variable listed in the function definition; an argument is the actual value passed when the function is called.

Answer : It ends the function and sends a value back to the caller, where it can be printed or stored, e.g. echo add(1, 16);

Answer : By returning an array (or object) and, if desired, destructuring it: [$lo, $hi] = stats($nums);

Answer : Values assigned to parameters in the definition, e.g. function greet($name, $greeting = "Namaste"), used when the caller omits that argument. They must come after required parameters.

Answer : Call by value passes a copy, so changes inside the function do not affect the original variable. Call by reference (parameter written as &$n) passes the variable itself, so changes are visible to the caller.

Answer : Declarations of the expected parameter and return types, e.g. function area(float $l): float. With declare(strict_types=1) PHP throws a TypeError for values of the wrong type.

Answer : A PHP 8 feature that lets you pass arguments by parameter name, in any order, and skip optional parameters: format(1234.5, prefix: "Rs. ").

Answer : A function that accepts any number of arguments using the ... operator, e.g. function total(...$numbers), where $numbers becomes an array.

Answer : Recursion is a function calling itself. A base case is a condition that returns without calling again; without it the function would call itself forever until memory runs out.

Answer : A function without a name, created with function (…) { … } and stored in a variable or passed as an argument (a closure). The use keyword imports outer variables into it.

Answer : A short closure introduced in PHP 7.4: fn($x) => $x * 2. It has a single expression body and automatically captures variables from the outer scope by value.

Answer : When a variable contains the name of a function, adding parentheses calls that function: $f = "strtoupper"; echo $f("php");
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which keyword defines a function?

Show Answer

Correct Answer : C. function
PHP functions are declared with the function keyword.

Q2. How do you pass a parameter by reference?

Show Answer

Correct Answer : B. &$n
The ampersand before the parameter passes the variable by reference.

Q3. What does function greet($n, $g = "Hi") mean?

Show Answer

Correct Answer : B. $g is optional with default "Hi"
A parameter with an assigned value has a default and is optional.

Q4. Which PHP 8 feature allows format(1234.5, prefix: "Rs. ")?

Show Answer

Correct Answer : B. Named arguments
Arguments are passed by parameter name.

Q5. Which is an arrow function?

Show Answer

Correct Answer : B. fn($x) => $x * 2
Arrow functions use the fn keyword and =>.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – User-defined functions. https://www.php.net/manual/en/functions.user-defined.php
  2. The PHP Group. (n.d.). PHP Manual – Function arguments. https://www.php.net/manual/en/functions.arguments.php
  3. The PHP Group. (n.d.). PHP Manual – Returning values. https://www.php.net/manual/en/functions.returning-values.php
  4. The PHP Group. (n.d.). PHP Manual – Anonymous functions. https://www.php.net/manual/en/functions.anonymous.php
  5. The PHP Group. (n.d.). PHP Manual – Arrow Functions. https://www.php.net/manual/en/functions.arrow.php