Home > Article > Backend Development > How to use each method in php
How to use each method in php?
each definition and usage
each() function returns the key name and key value of the current element, and moves the internal pointer backward.
The key name and key value of the element are returned to an array with four elements. Two elements (1 and Value) contain the key value, and two elements (0 and Key) contain the key name.
Related methods:
current() - 返回数组中的当前元素的值。 end() - 将内部指针指向数组中的最后一个元素,并输出。 next() - 将内部指针指向数组中的下一个元素,并输出。 prev() - 将内部指针指向数组中的上一个元素,并输出。 reset() - 将内部指针指向数组中的第一个元素,并输出。
Tip: The each() function is deprecated in PHP 7.2.0.
Syntax
each(array)
Parameters
array required. Specifies the array to use.
Return value: Returns the key name and key value of the current element. The element's key name and value are returned in an array with four elements. Two elements (1 and Value) contain the key value, and two elements (0 and Key) contain the key name. If there are no more array elements, the function returns FALSE.
Example 1
Same as the example at the top of the page, but this example outputs the entire array through a loop:
<?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); reset($people); while (list($key, $val) = each($people)) { echo "$key => $val<br>"; } ?>
Running result:
0 => Peter 1 => Joe 2 => Glenn 3 => Cleveland
Example 2
Demonstration of all related methods:
<?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 ?>
Running results:
Peter Joe Joe Peter Cleveland Glenn Glenn Peter Joe Array ( [1] => Joe [value] => Joe [0] => 1 [key] => 1 )
For more related knowledge, please follow PHP Chinese website! !
The above is the detailed content of How to use each method in php. For more information, please follow other related articles on the PHP Chinese website!