3
  $colors = array(
    'r' => 'a',
    'g' => 'b',
    'b' => 'c'
);

list($v, $k) = each($colors);

echo $v . " " . $k

Now the above prints r a which I'm surprise since I thought the 'list' construct only works for numerical array. Why does it work?

4
  • Because it works for all arrays. Commented Oct 14, 2012 at 20:36
  • 3
    @Felix Kling its in the documentation list() only works on numerical arrays and assumes the numerical indices start at 0. Commented Oct 14, 2012 at 20:36
  • @Baba what is this list Commented Oct 14, 2012 at 20:38
  • @jhonraymos it a very useful function to extract array values ... works like extract but you can specify variable name with list ... the examples in the PHP doc would help in1.php.net/manual/en/function.list.php Commented Oct 14, 2012 at 20:55

2 Answers 2

5

Yes you are right list() only works on numerical arrays and assumes the numerical indices start at 0. but he reason why your code is working its because of each.

each traverse an array therefore converted the keys to numerical example if you run the following :

$foo = array("r"=>"a");
$bar = each($foo);

echo "<pre>";
print_r($bar);

Output

Array
(
    [1] => a
    [value] => a
    [0] => r
    [key] => r
)

You can use that array('r' => 'a'); has been converted to array(0 => 'r', 1 => 'a'); therefore you can now use list since they now have numerical keys

FROM PHP DOC

each Return the current key and value pair from an array and advance the array cursor.

each Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.

Also

each() is typically used in conjunction with list() to traverse an array, here's an example:

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, you didn't explain it :)
2

Read the manual closer for each():

Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.

So when you do each($colors), the following is returned:

array(0 => 'r' => 1 => 'a', 'key' => 'r', 'value' => 'a')

Then list() takes the values for 0 and 1 and assigns them to $v and $k respectively. Make sense?

Comments

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.