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參考手冊