Table of Contents



Introduction

A function is a set of statements that perform a particular task (and optionally returns a value). In programming, we often find the need to reuse a certain block of code time and again. In this case, we can simply copy the chunk of code and place it into a function, and call the function by its name whenever we need to run the code. Functions make our programs less cluttered and more efficient, among other advantages:

  • Involve less typing.
  • Reduce syntax and other programming errors.
  • Decrease the loading time of program files.
  • Decrease execution time, because each function is compiled only once no matter how many times we call it.
  • Able to accept arguments and can therefore be used for general as well as specific cases.

Syntax of a Function

Following is the syntax of a Function.

Syntax

Defining a function.

1function function_name($arg_1, $arg_2, ... , $arg_n) {
2    statements;
3    return $val;
4}

where

  • the keyword function identifies the block of code that follows it as a function.
  • function_name is the name of the function that follows the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. Function names are case-insensitive.
  • $arg_1, $arg_2, ... , $arg_n are the optional arguments that are passed to the function and act as variables within the function.
  • statements is the chunk of code that performs the task(s) of the function.
  • return $val is optional and allows the function to return $val back to the statement that called the function.

ADVERTISEMENT



Built-in Functions

PHP comes with hundreds of built-in functions. To use such a function, we simply call it by name (with the relevant arguments). Note that functions can be written to take any number of arguments, including no argument.

In fact, we have already seen functions in action when we discussed string functions.

Example

Using the strlen() function to return the length of a string.

1<?php
2    echo strlen("Hello there!"); // including space and !
3?>
12

Example

Using the time() function (no argument).

1<?php
2    echo time();
3?>
1665038818

The time() function returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Example

Using the date() function with one argument.

1<?php
2    echo date("l");
3?>
Thursday

The argument "l" tells the function to return the current day of the week.

Example

Using the date() function with three arguments.

1<?php
2    echo date("F j, Y");
3?>
October 6, 2022

where the arguments are explained in the following table.

Parameter Description
F A full textual representation of a month (January through December).
j The day of the month without leading zeros (1 to 31).
Y A four digit representation of a year.
l A full textual representation of a day

Other arguments are possible. Refer to the function documentation .

Custom Functions

We can also define our own functions as the following examples illustrate.

Example

Writing a PHP function to output a header and attach a photo.

1<?php
2    function display_logo($img_file) {
3        echo "<h1 style='text-align:center;'>Learn PHP</h1>";
4        echo "<p style='text-align:center;'>";
5        echo "<img src='images/$img_file' width='30%' alt='PHP logo'>";
6        echo "</p>";
7    }
8    display_logo('php.png');
9?>

Learn PHP

PHP logo

The above function display_logo takes in one argument which is the name of an image (php.png). It searches for the image within the images folder which is a subfolder of the current folder where the PHP script resides. Calling the function will print out the string Learn PHP in h1 format and also display the php.png image, both horizontally centered.

In fact, calling the function outputs the following HTML code.

1<h1 style="text-align:center;">Learn PHP</h1>
2<p style="text-align:center ;">
3  <img src="pics/php.png" width="30%" alt="PHP logo" />
4</p>

Example

Writing a PHP function with two arguments.

1<?php
2    function intro($name, $country) {
3        echo "I am $name. I come from $country.<br>";
4    }
5    intro("Julia", "Taiwan");
6    intro("Eckart", "South Africa");
7?>
I am Julia. I come from Taiwan.
I am Eckart. I come from South Africa.

The following example takes in a numeric array as input argument and identify and print out the prime numbers. The code to compute primes is explained previously in another example.

Example

Writing a PHP function with array argument.

 1<?php
 2    function find_prime($arr) {
 3        foreach ($arr as $i) {
 4            for ($j = 2; $j < $i ; $j++) {
 5                if ($i % $j == 0) break; // not prime
 6            }
 7            if ($j==$i) echo "$i is prime.<br>";
 8        }
 9    }
10    $x = array(5,7,8,9,12,15,19,21,23,25,28,29); // input array
11    find_prime($x);
12?>
5 is prime.
7 is prime.
19 is prime.
23 is prime.
29 is prime.

ADVERTISEMENT



Default Argument Values

A function may define default values for arguments using syntax similar to assigning a variable. The default value is used only when the parameter is not specified. We therefore distinguish between two types of arguments:

  • Required arguments: without default value specified.
  • Optional arguments: with default value specified.

Example

Function with an optional argument.

1<?php
2    function greet($time = "morning") {
3        return "Hello! Good $time! <br>";
4    }
5    echo greet("afternoon");
6    echo greet();
7    echo greet("night");
8?>
Hello! Good afternoon!
Hello! Good morning!
Hello! Good night!
Note

Any optional arguments should be specified after any required arguments, otherwise they cannot be omitted from calls.

Example

Function with both required and optional arguments.

1<?php
2    function greeting($name, $time = "morning") {
3        return "Hi $name. Good $time! <br>";
4    }
5    echo greeting("Julian", "afternoon");
6    echo greeting("Julian");
7    echo greeting("afternoon"); // wrong sequence
8    echo greeting(); // error
9?>
Hi Julian. Good afternoon!
Hi Julian. Good morning!
Hi afternoon. Good morning!
Fatal error: Uncaught ArgumentCountError: Too few arguments to function greeting(), 0 passed in ...
  • In the above example, the first argument $name is required and the second argument $time is optional since a default value is provided.

  • We are allowed to pass in both arguments or just one argument (which should refer to the $name parameter).

  • In the third call: echo greeting("afternoon") passes in the wrong argument since PHP will assign "afternoon" to the $name parameter.

  • In the fourth call: echo greeting() produces an error since there is one required argument referring to the $name parameter.

On the other hand, if we were to place the optional parameter $time before the required parameter $name, an error will be reported.

Example

Error: placing optional parameter before required parameter .

1<?php
2    function greeting($time = "morning", $name) {
3        return "Hi $name. Good $time! <br>";
4    }
5    echo greeting("afternoon", "Julian");
6    echo greeting("Julian");
7?>
Deprecated: Required parameter $name follows optional parameter $time ...

Imagine a function has several optional arguments and we only want to pass in one optional argument. As of PHP 8.0.0, named arguments can be used to skip over multiple optional parameters.

Example

Using named arguments in functions.

1<?php
2    function greeting($time = "morning", $name = "Mr X") {
3        return "Hi $name. Good $time! <br>";
4    }
5    echo greeting();
6    echo greeting(name: "Julian"); // named argument
7?>
Hi Mr X. Good morning!
Hi Julian. Good morning!

Returning Values from Functions

We can write a function to return a single value or multiple values at once using the return statement.

Returning a Single Value

Example

Returning a single value from a function.

1<?php
2    function sum_of_squares($x, $y) {
3        $z = $x**2 + $y**2;
4        return $z;
5    }
6    echo "2^2 + 3^2 = " . sum_of_squares(2, 3) . "<br>";
7    echo "4^2 + 5^2 = " . sum_of_squares(4, 5) . "<br>";
8?>
2^2 + 3^2 = 13
4^2 + 5^2 = 41

ADVERTISEMENT



Returning Multiple Values

Technically, PHP functions do not allow us to return more than one value. However, we can use the list() function to assign values to a list of variables in one operation.

Consider the case where we want to write a function to return not just the sum of squares of two numbers, but also the sum of cubes and the sum of fourth powers. We will return an array that stores all three results. Thereafter, we assign the results to each of the three variables in a list by calling the function.

Example

Returning multiple values from a function using array() and list().

 1<?php
 2    function sum_of_powers($x, $y) {
 3        $z1 = $x**2 + $y**2; // squares
 4        $z2 = $x**3 + $y**3; // cubes
 5        $z3 = $x**4 + $y**4; // 4th powers
 6        return array($z1, $z2, $z3); // array of results
 7    }
 8    list($a, $b, $c) = sum_of_powers(2, 3); // assign to list
 9    echo "2^2 + 3^2 = $a <br>";
10    echo "2^3 + 3^3 = $b <br>";
11    echo "2^4 + 3^4 = $c <br>";
12?>
2^2 + 3^2 = 13
2^3 + 3^3 = 35
2^4 + 3^4 = 97
Tip

Since PHP 7.1.0, a simpler way to write list($a, $b, $c) is [$a, $b, $c].

We can also do away with the list() function altogether and assign the output array to a new array variable. The results will then be the elements of the new array which can be accessed as usual using indices.

Example

Returning multiple values from a function using array().

 1<?php
 2    function sum_of_powers($x, $y) {
 3        $z1 = $x**2 + $y**2; // squares
 4        $z2 = $x**3 + $y**3; // cubes
 5        $z3 = $x**4 + $y**4; // 4th powers
 6        return array($z1, $z2, $z3); // array of results
 7    }
 8    $powers = sum_of_powers(2, 3); // new array
 9    echo "Sum of squares: 2^2 + 3^2 = $powers[0] <br>";
10    echo "Sum of cubes: 2^3 + 3^3 = $powers[1] <br>";
11    echo "Sum of 4th powers: 2^4 + 3^4 = $powers[2] <br>";
12?>
Sum of squares: 2^2 + 3^2 = 13
Sum of cubes: 2^3 + 3^3 = 35
Sum of 4th powers: 2^4 + 3^4 = 97

Or even more incredibly, since the output from the function is really an array, we can immediately call the function with the desired arguments and treat it as an array.

Example

Returning multiple values from a function using array().

 1<?php
 2    function sum_of_powers($x, $y) {
 3        $z1 = $x**2 + $y**2; // squares
 4        $z2 = $x**3 + $y**3; // cubes
 5        $z3 = $x**4 + $y**4; // 4th powers
 6        return array($z1, $z2, $z3); // array of results
 7    }
 8    echo "Sum of squares: 2^2 + 3^2 = " . sum_of_powers(2, 3)[0] . "<br>";
 9    echo "Sum of cubes: 2^3 + 3^3 = " . sum_of_powers(2, 3)[1] . "<br>";
10    echo "Sum of 4th powers: 2^4 + 3^4 = " . sum_of_powers(2, 3)[2] . "<br>";
11?>
Sum of squares: 2^2 + 3^2 = 13
Sum of cubes: 2^3 + 3^3 = 35
Sum of 4th powers: 2^4 + 3^4 = 97

Passing Arguments by Reference

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

In the following example, the function fix_names() cleans up and removes all unwanted symbols from a list of names using the str_replace() function and thereafter converts the first character to uppercase using the ucfirst() function.

Example

Passing arguments to a function by reference.

 1<?php
 2    [$a1, $a2, $a3] = array("ja#ne", "l@i-ly", "an&dy");
 3    echo "$a1, $a2, $a3 <br>";
 4
 5    fix_names($a1, $a2, $a3);
 6    echo "$a1, $a2, $a3 <br>";
 7
 8    function fix_names(&$b1, &$b2, &$b3) // arguments passed by reference
 9    {
10        $unwanted = array("@","#","-","&");
11        $b1 = ucfirst(str_replace($unwanted, "", $b1));
12        $b2 = ucfirst(str_replace($unwanted, "", $b2));
13        $b3 = ucfirst(str_replace($unwanted, "", $b3));
14    }
15?>
ja#ne, l@i-ly, an&dy
Jane, Lily, Andy