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
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:
<html>
<body>
<?php
function writeName()
{
echo "Rahul Sharma";
}
echo "My name is ";
writeName();
?>
</body>
</html>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:
<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>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:
<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>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.
<html>
<body>
<?php
function add($x, $y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1, 16);
?>
</body>
</html>1 + 16 = 17
A function can return any type, including an array – useful for returning several values:
<?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";
?>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.
<?php
function greet($name, $greeting = "Namaste")
{
return "$greeting, $name!<br>";
}
echo greet("Asha");
echo greet("John", "Hello");
?>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.
<?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";
?>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.
<?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);
?>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:
<?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);
?>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.
<?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>";
}
?>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.
<?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");
?>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;
returnsends back a value and ends the function. - Default values make parameters optional;
&passes by reference. - Type declarations (
int,float|int,: string) andstrict_typesmake code safer. - PHP 8 named arguments:
format(1234.5, prefix: "Rs. "). ...collects variable arguments; recursion needs a base case; closures andfncreate 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)
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.
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.
- The PHP Group. (n.d.). PHP Manual – User-defined functions. https://www.php.net/manual/en/functions.user-defined.php
- The PHP Group. (n.d.). PHP Manual – Function arguments. https://www.php.net/manual/en/functions.arguments.php
- The PHP Group. (n.d.). PHP Manual – Returning values. https://www.php.net/manual/en/functions.returning-values.php
- The PHP Group. (n.d.). PHP Manual – Anonymous functions. https://www.php.net/manual/en/functions.anonymous.php
- The PHP Group. (n.d.). PHP Manual – Arrow Functions. https://www.php.net/manual/en/functions.arrow.php