PHP each() 函數
實例
返回當前元素的鍵名和鍵值,並將內部指針向後移動:
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
定義和用法
each() 函數返回當前元素的鍵名和鍵值,並將內部指針向後移動。
該元素的鍵名和鍵值返回到帶有四個元素的數組中。兩個元素(1 和 Value)包含鍵值,兩個元素(0 和 Key)包含鍵名。
相關的方法:
- current() - 返回數組中的當前元素的值。
- end() - 將內部指針指向數組中的最後一個元素,並輸出。
- next() - 將內部指針指向數組中的下一個元素,並輸出。
- prev() - 將內部指針指向數組中的上一個元素,並輸出。
- reset() - 將內部指針指向數組中的第一個元素,並輸出。
提示:each() 函數在 PHP 7.2.0 中被棄用了。
語法
each(array)
參數 | 描述 |
---|---|
array | 必需。規定要使用的數組。 |
技術細節
返回值: | 返回當前元素的鍵名和鍵值。該元素的鍵名和鍵值返回到帶有四個元素的數組中。兩個元素(1 和 Value)包含鍵值,兩個元素(0 和 Key)包含鍵名。如果沒有更多的數組元素,則函數返回 FALSE。 |
---|---|
PHP 版本: | 4+ |
更多實例
實例 1
與頁面頂部的實例相同,但是本例通過迴圈輸出整個數組:
$people = array("Peter", "Joe", "Glenn", "Cleveland");
reset($people);
while (list($key, $val) = each($people))
{
echo "$key => $val<br>";
}
實例 2
所有相關方法的演示:
$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
