PHP Functions Tutorial

In this tutorial we learn about functions in PHP and how they help us break up our application logic into smaller sections for easy reuse throughout our code.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a function?

As an application becomes bigger, and more complex, we need ways to separate our code into smaller sections of logic.

We typically want a section of code to only be responsible for a single task, or to be easily reusable. A function is a wrapper for such a section of logic.

As an example, let’s consider some simple functionality. The section of code below, is responsible to evaluate if a number is even or odd.

Example: typical section of code logic
<?php

// Number to check
$num = 5;

// If the number can be divided by two
// without a remainder, it's an even number
if ($num % 2 == 0) {
    echo $num . " is an even number.<br>";
} else {
    echo $num . " is an odd number.<br>";
}

?>

If we want to do the same evaluation on more numbers, we would have to rewrite the whole section of logic. To avoid this problem, we can wrap the logic inside a function.

We’ve used some built-in PHP functions earlier in the tutorial course, such as the array() function. When we consider the array() function, we know that we can pass values between the parentheses, and it will create an array for us.

We can create such functions with our own logic inside.

How to define a function

Functions can be simple or complex based on the logic it contains. We will start with a simple example, the function will neither receive nor return data.

Syntax:
function funcName() {
    section of logic to execute
}

The example that follows will hypothetically alert a user when they receive a message.

Example: alert a user
<?php

function alertUser() {
    echo "You've got mail.";
}

?>

In the example above, we tell the function to print a message to the page. If you ran the example in a browser however, you would notice it didn’t print the message to the page.

How to call a function

We may have defined the function, but we did not actually use it. To use a function, we must call it, which will execute the function.

Syntax:
// Function definition
function funcName() {
    section of logic to execute
}

// Function call
funcName();

In its simplest form, we can just write the function name, followed by parentheses ( ) , and a semicolon to terminate the statement.

Example: call/use a function
<?php

// Define the functionality to
// alert the user if they have
// a message
function alertUser() {
    echo "You've got mail.";
}

// Actually use the function
// to alert the user
alertUser();

?>

In the example above, we call the function and it prints the alert message to the page.

How to define a function with arguments

We know from using the array() function, that we can give a function some values to use in its logic.

To do this, we need to create parameters, which are temporary variables that will hold the values to use inside the logic. It’s similar to the temporary variable in a foreach loop.

Syntax:
function funcName(param1, param2, param3, ...) {
    section of logic to execute
}

If we want to use more than one parameter, we need to separate them with commas.

Example: function with an argument
<?php

function alertUser($user) {
    echo $user . ". You've got mail.";
}

?>

In the example above, we create a parameter (a temporary variable) to take the user’s name when the function is called. The user’s name is used in the echo statement to personalize the message.

If we try to call the function now, the same way we did before, the interpreter would raise an error.

Example: no argument specified
<?php

function alertUser($user) {
    echo $user . ". You've got mail.";
}

alertUser();

?>
Output: Missing argument error
 Fatal error: Uncaught ArgumentCountError: Too few arguments to function alertUser(), 0 passed...

The output above, means that the interpreter expects the function call to pass values (arguments) to the function, that corresponds to the parameters.

The function expects a username. If we pass a name between the parentheses, the interpreter will replace of instances of $user with the username, and the username will be printed to the page.

Example:
<?php

function alertUser($user) {
    echo $user . ". You've got mail.";
}

alertUser("John");

?>

When we run the example above, it prints the username “John” with the message.

How to call a function multiple times

The beauty of a function is that we can call it multiple times, without having to rewrite the logic.

Example: multiple function calls
<?php

function alertUser($user) {
    echo $user . ". You've got mail.<br>";
}

alertUser("John");
alertUser("Jane");
alertUser("Jack");
alertUser("Jill");

?>

In the example above, we call the function four times, and each time we pass a different username to the function.

A more practical situation will have users in a database, or array. We can call the function inside a loop to handle a large amount of calls.

Example: loop multiple function calls
<?php

// Collection of users
$user = ["John", "Jane", "Jack", "Jill"];

// Loop through users and alert each
foreach($user as $username) {
    alertUser($username);
}

// Function definition
function alertUser($user) {
    echo $user . ". You've got mail.<br>";
}

?>

The IsEvenOdd() custom function

At this point, we have learned enough about functions to convert the logic at the start of the lesson, into a function.

As a challenge, try to convert the odd or even logic into a function. If your function doesn’t work, or behaves differently than what you expect, look at our function and see if yours match.

Example: custom function
<?php

function isEvenOdd($num) {
    if ($num % 2 == 0) {
        echo $num . " is an even number.<br>";
    } else {
        echo $num . " is an odd number.<br>";
    }
}

isEvenOdd(5);
isEvenOdd(10);
isEvenOdd(27);
isEvenOdd(98654);

?>

How to return a value from a function

A function can return a value, or values, if we need it to. We use the return keyword in front of whatever we want to return out of the function.

Syntax:
function funcName(param1, param2, param3, ...) {
    section of logic to execute

    return something
}
Example: return a value
<?php

function canVote($age) {
    if($age >= 18) {
        return true;
    } else {
        return false;
    }
}

?>

In the example above, we evaluate if a user is old enough to vote. If the user is old enough to vote, the function will return true, otherwise it will return false.

Now that our function returns something, we can use the result of the function to control the flow of the application.

Example: using the returned value
<?php

$userAge = 17;

if(!canVote($userAge)) {
    echo "Sorry, you are not allowed to vote yet.";
}

function canVote($age) {
    if($age >= 18) {
        return true;
    } else {
        return false;
    }
}

?>

The example above is somewhat impractical, but it demonstrates how powerful functions can be.

Function return types

In strongly typed languages, such as C#, we have to specify the type of value that a function can return.

Example: C# return type
using System;

namespace Functions
{
    class Program
    {
        static void Main(string[] args)
        {
            isEvenInt(5);

            Console.ReadLine();
        }

        static bool isEvenInt(int num)
        {
            if (num % 2 == 0)
                return true;
            else
                return false;
        }
    }
}

When we look at the example above, we can see that the function isEvenInt() has the bool keyword written in front of it.

This means that the function can only return a boolean value of true or false. If we try to return another type, the compiler will raise an error.

In PHP, we can also restrict the type of the return value, although the syntax is different. After the function parentheses, we write a colon and then the type.

Syntax:
function functionName(param1, param2, ...) : TYPE {
    function body
}
Example: restrict a function's return type
<?php

$userAge = 17;

if(!canVote($userAge)) {
    echo "Sorry, you are not allowed to vote yet.";
}

function canVote($age) : bool {
    if($age >= 18) {
        return true;
    } else {
        return false;
    }
}

?>

In the example above, the function is restricted to only return a boolean value. If we change the returned value to a string, the function would still try to return a boolean.

Example:
<?php

function canVote($age) : bool {
    if($age >= 18) {
        return "True string";
    } else {
        return "False string";
    }
}

echo canVote(17);

?>

In the example above, the interpreter prints the number 1 to the page, where 1 represents the boolean value of true.

Not only is the result wrong, but the function didn’t print the returned string.

If we change the restriction from bool to string, the correct string value will be printed to the page.

Example:
<?php

function canVote($age) : string {
    if($age >= 18) {
        return "True string";
    } else {
        return "False string";
    }
}

echo canVote(17);

?>

Returning the wrong type can cause all sorts of problems within our code. It’s important to remember to return the same type as specified.

This feature is only available to PHP v7.0+.

Summary: Points to remember

  • A function separates code into smaller sections of logic.
  • A function must be defined with the function keyword.
  • An existing function can be used by calling the function with any arguments it may require between parentheses.
  • A function’s arguments are only available in the local scope (inside the function’s code block).
  • A function can return a single value by using the return statement.
  • A function can restrict its return value with : type.