How would you return an array from a function in PHP?

If you have a function and you want to return multiple values from that function then you can easily return an array from the function. This is what it would look like:

function someFunc( ) {

$aVariable = 10;
$aVariable2 = 20;

return array($aVariable, $aVariable2);
}

How to retrieve the values returned from a function in PHP

You will probably want to retrieve the values returned from the function after you call it. What is the best way to do this? Well, there is actually a nice way to do this using the list function in PHP. Here is an example of how to retrieve the values returned from an array in a function – assuming that we are calling the same someFunc function that we showed above:

list($var1, $var2)  = 
     someFunc( ); 

//will print out values from someFunc
echo "$var1 $var2"; 

Now, $var1 and $var2 will hold the same values as $aVariable and $aVariable2 from the function someFunc.

Another option for retrieving the values returned from a function in PHP

Another possibility is to just store the return values in an array as well – here is an example:

$results = someFunc();

echo $results[0];

echo $results[1];

Note that in the example above everything returned from the call to someFunc is stored in the $results array – and the echo statements will output the values returned from someFunc.




Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.