Learning PHP – Lesson 6 – Define PHP Functions
In this lesson we are going to introduce how to define PHP functions. A function is a reusable block of code that performs a specific action. Takes some parameters as input, performs some operations and returns an output. Examples of functions are print_r, array_combine, array_merge that we already used in the past lessons. If you missed here is a list of the previous articles
Other articles of the same series
Let’s dive into the PHP functions
In this article we are going to explore
- How to declare a PHP function
- How to use PHP function arguments
- How to return values from PHP functions
- How to pass function arguments by reference
- How to return more than one value using PHP functions
To declare a function we have to start with the word function
function functionName() {
// code
}
or
function functionName(param1, param2, ...paramN) {
// code
}
Declare a function
Let’s declare a function that print a message
<?php
function printMessage() {
echo "Hello from the function\n";
}
printMessage();
?>
Nothing interesting so far. If we want to make the functions really powerful we should introduce the arguments, this will make the functions really flexible.
Function arguments
The function arguments are parameters that we can use to pass values to a function. In other words an argument is a variable that we are giving to the function so that can be used. Let’s see with an example
<?php
function printMessage($argument) {
echo "$argument\n";
}
// print Hello
printMessage("Hello");
//print Hello World
printMessage("Hello World");
// print a separator
printMessage("----------------------------------");
// print within a loop
for ($i = 0; $i < 5; $i++) {
printMessage("Iteration $i");
}
?>
As you can see passing the arguments makes the function super flexible. In our previous example $argument was the function argument, however if we try to call the function without an argument it will generate an error:
<?php
printMessage();
?>
//output
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function printMessage(), 0 passed in /var/www/localhost/p.php on line 14 and exactly 1 expected in /var/www/localhost/p.php:3
Stack trace:
#0 /var/www/localhost/p.php(14): printMessage()
#1 {main}
thrown in /var/www/localhost/p.php on line 3
Returning values
The functions we have seen so far are yes flexible but are not doing so much. To make a real use of a function it must perform an action on the arguments and return a value. Returning a value it means that we can associate the function result to a variable by using the keyword return
<?php
function sumNumbers($num1, $num2) {
$value_to_return = $num1 + $num2;
return $value_to_return;
}
$sum = sumNumbers(18, 21);
echo "Sum: $sum\n";
?>
As you can see now $sum has the result of the function operation.
In our previous article we had this block of code
<?php
// sum all the numbers in $array
$array = [2,3,4,5,7,8,90,19,23];
$counter = 0;
for($i = 0; $i < sizeof($array); $i++){
$counter = $counter + $array[$i];
echo "Iteration $i, array item: {$array[$i]}, Total: $counter\n";
}
echo $counter;
?>
With small adjustments we can easily convert to a function and reuse with different arrays
<?php
function sumArrayNumbers($array) {
$counter = 0;
for($i = 0; $i < sizeof($array); $i++){
$counter = $counter + $array[$i];
}
return $counter;
}
$array_to_sum_1 = [2,3,4,5,7,8,90,19,23];
$sum1 = sumArrayNumbers($array_to_sum_1);
echo "total: $sum1\n";
$array_to_sum_2 = [20,31,42,15,734,8,90,19,23];
$sum2 = sumArrayNumbers($array_to_sum_2);
echo "total: $sum2\n";
?>
//output
total: 161
total: 982
Passing function arguments by reference
By default all the PHP function arguments are passed by value, that means that if the value of the argument is changed within the function, this is not being reflected outside. Let’s have a look at this small example
<?php
function value_pass_func($some_arg) {
for($i=0; $i<5; $i++) {
$some_arg = $some_arg + $i;
echo "Value of some_arg in the function is: $some_arg\n";
}
}
$some_arg = 0;
value_pass_func($some_arg);
echo "some_arg outside the function: $some_arg\n";
?>
// output
Value of some_arg in the function is: 0
Value of some_arg in the function is: 1
Value of some_arg in the function is: 3
Value of some_arg in the function is: 6
Value of some_arg in the function is: 10
some_arg outside the function: 0
You might be surprised or not but that’s the way it works. The argument $some_arg is passed as a copy and any change will be lost as soon the function ends. If you want, PHP offers you the ability to pass arguments by reference. Passing argument by reference it means that the argument we are passing is not a copy but is instead a (memory) reference of the variable. In other words we are giving to the function the access to the memory location of the argument we are passing and all the changes will be reflected also outside. See the example below
<?php
function value_pass_func(&$some_arg) {
for($i=0; $i<5; $i++) {
$some_arg = $some_arg + $i;
echo "Value of some_arg in the function is: $some_arg\n";
}
}
$some_arg = 0;
value_pass_func($some_arg);
echo "some_arg outside the function: $some_arg\n";
?>
// output
Value of some_arg in the function is: 0
Value of some_arg in the function is: 1
Value of some_arg in the function is: 3
Value of some_arg in the function is: 6
Value of some_arg in the function is: 10
some_arg outside the function: 10
As you can see all we had to do (if you didn’t notice) was to add an & (line #3) in front of the argument definition for the function. Job done!
This approach is often used because you want to return (or manipulate) more than one variable during the function execution, unfortunately (but here I would say…point of views!) PHP can’t return more than one value like python. However we can achieve that by using the list keyword.
Functions that return more than one value
In PHP functions can only return one value, however there are different approaches that are helping to overcome this limitation. One is, like we have seen in the section above, using reference arguments, the other approach is using a combination of functions. In the example below I’m considering the “classic” swap function and convert into a function that will return more than one value.
<?php
$a = 10;
$b = 15;
// swap start
$temp = $a;
$b = $a;
$b = $temp;
?>
// end result $a = 15 and $b = 10
The swap function can be converted into a function that returns an array with the inverted elements, and by that I mean that if the order of the arguments is ($a, $b) they are returned into an array as [$b, $a]. The real magic happens outside the function when calling the PHP function list. The list function stores the array elements into the different variables (in our case $a and $b) instead of storing the array itself.
<?php
function swap($a, $b) {
return array($b, $a);
}
$a = 1;
$b = 50;
list($a, $b) = swap($a, $b);
echo "a = $a, b = $b\n";
?>
Job done!
That’s mostly it on the PHP functions. I hope you enjoyed and if so, share and help us grow! if not, share equally
Share this content: