Returning multiple values from a PHP function.

This is a tutorial on how to return multiple values from a PHP function. In certain circumstances, you might need your custom PHP function to return more than one value. This guide discusses the best approach to take.

You can’t return more than one value.

A PHP function can take in multiple parameters, but it can only return one value. This means that the following example will not work:

//This will not work.
function my_function(){
    return 'first string';
    return 'second string';
}

The function above will “work” in the sense that it won’t cause any errors. However, if you attempt to call it, you will find that only the first return statement gets executed.

This is because the whole purpose of the return statement is to return control of the script to the calling module. Once the first return statement is executed, the function “ends”, so to speak.

If you call the function above, you will see that the returned result is always “first string”.

Return the values in an array.

Native PHP functions such as getimagesize solve this particular problem by returning an array of values instead of a single scalar value.

We can emulate this approach quite easily.

Let’s say for example that we want to create a PHP function that returns the first and last character of a given string:

/**
 * Function that returns the first and last character
 * of a string.
 *
 * @param $string The string in question.
 * @return array An array containing the first and last characters.
 */
function getFirstAndLast($string){
    $firstCharacter = substr($string, 0, 1);
    $lastCharacter = substr($string, -1);
    return array(
        'first' => $firstCharacter,
        'last' => $lastCharacter
    );
}

The function above finds the first character of a PHP string and then assigns to an array key called “first”. Similarly, it assigns the last character to an array key called “last”.

This array is then returned.

An example of this function in use:

//Call our function.
$result = getFirstAndLast('Hello');
//var_dump the result.
var_dump($result);

If you run the PHP above, you will see the following result:

This means that you can access the returned values like so:

echo 'First character: ' . $result['first'] . '<br>';
echo 'Last character: ' . $result['last'] . '<br>';

Hopefully, this guide cleared a few things up!