PHP each() 函数
实例
返回当前元素的键名和键值,并将内部指针向前移动:
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>
定义和用法
each() 函数返回当前元素的键名和键值,并将内部指针向前移动。
该元素的键名和键值返回到带有四个元素的数组中。两个元素(1 和 Value)包含键值,两个元素(0 和 Key)包含键名。
相关的方法:
- current() - 返回数组中的当前元素的值。
- end() - 将内部指针指向数组中的最后一个元素,并输出。
- next() - 将内部指针指向数组中的下一个元素,并输出。
- prev() - 将内部指针指向数组中的上一个元素,并输出。
- reset() - 将内部指针指向数组中的第一个元素,并输出。
语法
each(array)
参数 | 描述 |
---|---|
array | 必需。规定要使用的数组。 |
技术细节
返回值: | 返回当前元素的键名和键值。该元素的键名和键值返回到带有四个元素的数组中。两个元素(1 和 Value)包含键值,两个元素(0 和 Key)包含键名。如果没有更多的数组元素,则函数返回 FALSE。 |
---|---|
PHP 版本: | 4+ |
更多实例
实例 1
与页面顶部的实例相同,但是本例通过循环输出整个数组:
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
reset($people);
while (list($key, $val) = each($people))
{
echo "$key => $val<br>";
}
?>
$people = array("Peter", "Joe", "Glenn", "Cleveland");
reset($people);
while (list($key, $val) = each($people))
{
echo "$key => $val<br>";
}
?>
实例 2
所有相关方法的演示:
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>"; // The current element is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
echo current($people) . "<br>"; // Now the current element is Joe
echo prev($people) . "<br>"; // The previous element of Joe is Peter
echo end($people) . "<br>"; // The last element is Cleveland
echo prev($people) . "<br>"; // The previous element of Cleveland is Glenn
echo current($people) . "<br>"; // Now the current element is Glenn
echo reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward
?>
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>"; // The current element is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
echo current($people) . "<br>"; // Now the current element is Joe
echo prev($people) . "<br>"; // The previous element of Joe is Peter
echo end($people) . "<br>"; // The last element is Cleveland
echo prev($people) . "<br>"; // The previous element of Cleveland is Glenn
echo current($people) . "<br>"; // Now the current element is Glenn
echo reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter
echo next($people) . "<br>"; // The next element of Peter is Joe
print_r (each($people)); // Returns the key and value of the current element (now Joe), and moves the internal pointer forward
?>
完整的 PHP Array 参考手册