-1

This one is stumping me. I'm trying to figure out why this doesn't work. I have a function that returns an array. I want to use list to put that array into variables. It doesn't seem to be working. Here is what I have:

function($x, $y, $z){
    return array('x' => $x, 'y' => $y, 'z' => $z);
}

list($x, $y, $z) = function($x, $y, $z);

That however does not seem to return variables back into the $x, $y, $z variables.

Instead I have to do this:

function($x, $y, $z){
    return array('x' => $x, 'y' => $y, 'z' => $z);
}

$array = function($x, $y, $z);
$x = $array['x'];
$y = $array['y'];
$z = $array['z'];

Anything I am doing wrong in this particular case? Is there some kind of limitation to the list function that would prevent this from working? (Note, above is obviously not a real function or defined correctly and is only presented as an example).

3 Answers 3

2

From the manual:

list() only works on numerical arrays and assumes the numerical indices start at 0.

Simply change the keys to be numerical and this will work fine:

function($x, $y, $z){
    return array($x, $y, $z);
    // OR: return array_values(array('x' => $x, 'y' => $y, 'z' => $z));
}

list($x, $y, $z) = function($x, $y, $z);
1
  • Thanks for the note about the array indices. That allowed me to solve my problem by using array_values. Commented Sep 22, 2014 at 2:32
1

You could use extract function to create variables like below:

function foo($x, $y, $z){
    return array('x' => $x, 'y' => $y, 'z' => $z);
}

extract(foo($x, $y, $z));

// or you have to use the values of the array returned.
list($x, $y, $z) = array_values(foo($x, $y, $z));
0

Since the list function only works with either numerical (or no keys), you have to strip the keys from the array before being able to insert them into the variables using list.

list($x, $y, $z) = array_values(function($x, $y, $z));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.