This article demonstrates how to return multiple values from a function in PHP.

Traditionally, functions in PHP allow you to return only one value at a time. However, you might need to return multiple values from a function sometimes. Fortunately, there are a few workarounds for returning multiple values in PHP.

1. Using an array

The first workaround is to use an array for storing all the required fields, and return that array from the function. For example, the following solution stores all values to be returned in an array and returns it from the function: It then uses the list construct to access the array values. list() can work on numerical arrays and assign variables as if they were an array.

Download  Run Code

 
To make the content more clear, you can use an associative array. Here’s a cleaner version of the above code that returns the field information to the caller.

Download  Run Code

2. Using an object

Instead of returning an array, you can also return an object from the function. To demonstrate, the following PHP snippet creates an instance of stdClass class with the new operator, adds dynamic properties for the required fields, and finally returns the object from the function. This is useful as it passes field information to the caller.

Download  Run Code

3. Passing by reference

Finally, you can pass multiple values to the function by reference, which allows the function to modify the variable. All changes made to the reference variable inside the function will be reflected in the original variable itself. The following solution demonstrates how to declare the function parameters as references. Note that there is no reference sign on a function call, but only on function definitions.

Download  Run Code

That’s all about returning multiple values from a function in PHP.