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:

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:

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:

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

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

Hopefully, this guide cleared a few things up!

Facebook Comments