(PHP 4, PHP 5, PHP 7)
each — 返回数组中当前的键/值对并将数组指针向前移动一步
本函数已自 PHP 7.2.0 起被废弃,并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。
返回数组中当前的键/值对并将数组指针向前移动一步
在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset() 。
array输入的数组。
返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为0,1,key和 value。单元 0 和
key 包含有数组单元的键名,1 和
value 包含有数据。
如果内部指针越过了数组的末端,则 each() 返回 false 。
示例 #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() 结合使用来遍历数组,例如:
示例 #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
因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。
each() 也接受对象,但可能会返回意外结果。因此不建议使用 each() 遍历对象属性。
Following the obsolescence of the each() function, here is a way to correct your source codes:
If you use each() in a while loop like this:
while (list($Key,$Value)=@each($Array)){
....
}
you have to replace with
foreach ($Array as $Key => $Value){
....
}
In the same minds.
while (list(,$Value)=@each($Array)){
....
}
will become
foreach ($Array as $Value){
....
}each was deprecated because it exposed too much of the internal implementation details, blocking language development. ("We can't do X because it would break each().")
https://wiki.php.net/rfc/deprecations_php_7_2#each
If you want an array pointer, maintain it yourself. Probably a good idea anyway, because then it's visible in the code.Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().
It works like this:
<?php
$arr = array('foo', 'bar');
foreach ($arr as $value) {
echo "The value is $value.";
}
$arr = array('key' => 'value', 'foo' => 'bar');
foreach ($arr as $key => $value) {
echo "Key: $key, value: $value";
}
?>Hello, since each() and list() often "betray" very old applications, I simply recommend not to use them anymore.
If you want to assign variables based on an associative array,
Replace this:
while(list ($key, $value) = each ($my_array)) {
$$key = $value;
}
with this:
foreach ($my_array as $key => $value) {
$$key = $value;
}Rector has an automated fix ('ListEachRector') to migrate away from `each()`:
https://github.com/rectorphp/rector/blob/master/docs/AllRectorsOverview.md#listeachrector
If you look at the code example you'll see this is even quite simple to do by hand.