each

(PHP 4, PHP 5, PHP 7)

each返回数组中当前的键/值对并将数组指针向前移动一步

Warning

This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

说明

each ( array &$array ) : array

返回数组中当前的键/值对并将数组指针向前移动一步

在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()

参数

array

输入的数组。

返回值

返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为01keyvalue。单元 0key 包含有数组单元的键名,1value 包含有数据。

如果内部指针越过了数组的末端,则 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

Caution

因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。

Warning

each() will also accept objects, but may return unexpected results. Its therefore not recommended to iterate though object properties with each().

参见

  • key() - 从关联数组中取得键名
  • list() - 把数组中的值赋给一组变量
  • current() - 返回数组中的当前单元
  • reset() - 将数组的内部指针指向第一个单元
  • next() - 将数组中的内部指针向前移动一位
  • prev() - 将数组的内部指针倒回一位
  • foreach
  • Object Iteration