PHP 'list' working on non-numerical arrays?
Frage
$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?
Lösung
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
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:
Andere Tipps
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?