The existence of functions in PHP makes it a very strong programing language.
With over 1000 built-in functions and the ability to create custom ones, PHP offers extensive flexibility and power for developers.
Built-in Functions
PHP includes over 1000 built-in functions that can be directly called within a script to accomplish specific tasks.
Custom Functions
In addition to the built-in PHP functions, you can also create your own functions.
- A function is a block of statements that can be reused multiple times within a program.
- Functions do not execute automatically when a page loads.
- A function is executed only when it is called.
Create a Function
A user-defined function is declared by starting with the keyword function
, followed by the function's name.
A function name must begin with a letter or an underscore. Function names are not case-sensitive.
Choose a name for the function that clearly describes its purpose!
The opening curly brace {
marks the start of the function code, and the closing curly brace }
marks the end.
<?php
function greetUser() {
echo "Welcome to the platform!";
}
?>
Call a Function
To call the function, simply write its name followed by parentheses ()
.
<?php
function showMessage() {
echo "Hi there, welcome!";
}
showMessage(); // Calling a function
?>
/*
Output:
Hi there, welcome!
*/
Function Arguments
Information can be passed to functions through arguments, which are similar to variables.
Arguments are listed after the function name within parentheses. You can define multiple arguments by separating them with commas.
For instance, the function displayFullName()
in the following example takes one argument $fname
. When calling the displayFullName()
function, we provide a specific name (e.g., "Sami"), which is then utilized inside the function to output various first names with a consistent last name.
<?php
function displayFullName($fname) {
echo "$fname Johnson.<br>";
}
displayFullName("Sami");
displayFullName("Bob");
displayFullName("Charlie");
displayFullName("Dana");
displayFullName("Eve");
?>
/*
Output:
Sami Johnson.
Bob Johnson.
Charlie Johnson.
Dana Johnson.
Eve Johnson.
*/
Below example shows a function displayInfo()
with two arguments named $fname
and $birthyear
.
<?php
function displayInfo($fname, $birthYear) {
echo "$fname Smith. Born in $birthYear.<br>";
}
displayInfo("Alice", "1990");
displayInfo("Bob", "1985");
displayInfo("Charlie", "1992");
?>
/*
Output:
Alice Smith. Born in 1990.
Bob Smith. Born in 1985.
Charlie Smith. Born in 1992.
*/
Default Argument Value
To pass a default argument value, set it directly inside the ()
, as shown below.
<?php
function setWidth($minWidth = 100) {
echo "The width is: $minWidth <br>";
}
setWidth(500);
setWidth(); // will use the default value of 100
setWidth(250);
setWidth(150);
?>
/*
Output:
The width is: 500
The width is: 100
The width is: 250
The width is: 150
*/
Returning values
To have a function return a value, use the return
statement.
<?php
function addNumbers($a, $b) {
$result = $a + $b;
return $result;
}
echo "15 + 25 = " . addNumbers(15, 25) . "<br>";
echo "20 + 30 = " . addNumbers(20, 30) . "<br>";
echo "5 + 15 = " . addNumbers(5, 15);
?>
/*
Output:
15 + 25 = 40
20 + 30 = 50
5 + 15 = 20
*/
Passing Arguments by Reference
In PHP, arguments are typically passed by value, meaning a copy of the value is used within the function. This copy prevents direct modification of the original variable passed to the function.
However, when a function argument is passed by reference, any changes made to the argument directly affect the original variable that was passed in. To designate a function argument as a reference, you use the &
operator.
Use pass-by-reference arguments to modify variables directly within a function.
<?php
function increaseByTen(&$number) {
$number += 10;
}
$value = 4;
increaseByTen($value);
echo $value;
?>
/*
Output:
14
*/
Variable Number of Arguments
By prefixing the function parameter with the ...
operator, the function can accept a variable number of arguments. This type of function is known as a variadic function.
The variadic function parameter is treated as an array containing all the passed arguments.
<?php
function calculateTotal(...$numbers) {
$total = 0;
$count = count($numbers);
for ($i = 0; $i < $count; $i++) {
$total += $numbers[$i];
}
return $total;
}
$result = calculateTotal(10, 5, 15, 5, 10);
echo $result;
?>
/*
Output:
45
*/
You can only have one argument with variable length, and it has to be the last argument.
The variadic argument must be the last parameter in the function's parameter list.
<?php
function greetFamilyMembers($surname, ...$names) {
$message = "";
$count = count($names);
for ($i = 0; $i < $count; $i++) {
$message .= "Hello, $names[$i] $surname.<br>";
}
return $message;
}
$result = greetFamilyMembers("Smith", "Alice", "Bob", "Charlie");
echo $result;
?>
/*
Output:
Hello, Alice Smith.
Hello, Bob Smith.
Hello, Charlie Smith.
*/
You will encounter an error if the variadic argument is not positioned as the last argument in the function's parameter list.
PHP is a Loosely Typed Language
In the examples above, PHP dynamically assigns a data type to variables based on their values, without requiring explicit declaration. This flexibility allows operations such as adding a string to an integer without generating an error.
Starting from PHP 7, type declarations were introduced, offering the ability to specify the expected data type when defining a function. Enabling strict
type declaration ensures that PHP throws a Fatal Error if there is a mismatch in data types.
To enforce strict
type checking, you must include declare(strict_types=1);
at the very beginning of your PHP file.
In the example below, we attempt to pass both a number and a string to a function while adhering to strict
type declarations:
<?php
declare(strict_types=1); // Enabling strict typing
function sumIntegers(int $x, int $y) {
return $x + $y;
}
try {
echo sumIntegers(7, "4 apples");
} catch (TypeError $e) {
echo "Error: " . $e->getMessage();
}
?>
/*
Error: Argument 2 passed to sumIntegers() must be of the type
integer, string given, called in /home/php/script.php on line 9
*/
PHP Return Type Declarations
In PHP 7, Type Declarations for the return
statement are also supported. Similar to type declarations for function arguments, enabling strict mode will result in a Fatal Error if there's a type mismatch.
To specify a return type for a function, you add a colon :
followed by the type just before the opening curly brace {
when declaring the function.
Consider the following example where we define the return type for a function:
<?php
declare(strict_types=1); // Enforcing strict typing
function calculateSum(float $x, float $y) : float {
return $x + $y;
}
$result = calculateSum(3.5, 4.7);
echo "$result";
?>
/*
Output:
8.2
*/
You can specify a different return type than the argument types, but ensure that the actual return value matches the specified return type.
<?php
declare(strict_types=1); // Enforcing strict typing
function sumAsInteger(float $x, float $y) : int {
return (int)($x + $y);
}
$result = sumAsInteger(3.7, 2.8);
echo $result;
?>
/*
Output:
6
*/