How to Return More Than One Value From a Function in PHP

Here is a cool trick you might not know if you want to return multiple values from a function and assign them to variables with different names each.

Here Is How It Works:

Say you have the following function returning an array.

function SomeFunction()
{
   /** lots of code   **/
   return array($value1, $value2, $value3);
}

Now to assign each value to a different variable, in the order in which you returned them, do the following.

list($variable1,$variable2,$variable3)=SomeFunction();
Returning an Array of Associative Keys

You could just assign SomeFunction() to a variable, which would make it an array, but you would then have to access each value using numeric keys e.g $var[0] would hold $value1. A better approach if you want to do this would be to make associative keys in the returning array:

function SomeFunction()
{
   /** lots of code   **/
   return array('key1'=>$value1, 'key2'=>$value2, 'key3'=>$value3);
}

Usage:

$someArray=SomeFunction();
echo $someArray['key1']; // shows $value1

Which method do/will you use the most?

Leave a Reply