(PHP 4, PHP 5)
each — 返回数组中当前的键/值对并将数组指针向前移动一步
&$array
)
返回 array
数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为
0,1,key
和 value。单元 0 和
key 包含有数组单元的键名,1 和
value 包含有数据。
如果内部指针越过了数组的末端,则 each() 返回 FALSE
。
Example #1 each() 例子
<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>
$bar 现在包含有如下的键/值对:
Array { [1] => bob [value] => bob [0] => 0 [key] => 0 }
<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>
$bar 现在包含有如下的键/值对:
Array { [1] => Bob [value] => Bob [0] => Robert [key] => Robert }
each() 经常和 list() 结合使用来遍历数组,例如:
Example #2 用 each() 遍历数组
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>
以上例程会输出:
a => apple b => banana c => cranberry
在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()。
因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。
array
The input array.
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.
If the internal pointer for the array points past the end of the
array contents, each() returns
FALSE
.
Example #3 each() examples
<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>
$bar now contains the following key/value pairs:
Array ( [1] => bob [value] => bob [0] => 0 [key] => 0 )
<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>
$bar now contains the following key/value pairs:
Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert )
each() is typically used in conjunction with list() to traverse an array, here's an example:
Example #4 Traversing an array with each()
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>
以上例程会输出:
a => apple b => banana c => cranberry
Because assigning an array to another variable resets the original arrays pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.
each() will also accept objects, but may return unexpected results. Its therefore not recommended to iterate though object properties with each().