PHP each() Function
The PHP each() function returns the current key and value pair from an array and advance the array cursor. After each execution of this function, the array cursor advances to the next element of the array, or past the last element if the end of the array has been reached.
Syntax
each(array)
Parameters
array |
Required. Specify the input array. |
Return Value
Returns the current key and value pair from the array array. If the internal pointer for the array points past the end of the array contents, it returns false.
Example: each() example
The example below shows the usage of each() function.
<?php $Arr = array("John", 25, "London"); $key_value = each($Arr); print_r($key_value); ?>
The output of the above code will be:
Array ( [1] => John [value] => John [0] => 0 [key] => 0 )
Example: using with associative array
Consider the example below where this function is used with an associative array.
<?php $Arr = array("name"=>"John", "age"=>25, "city"=>"London"); $key_value = each($Arr); print_r($key_value); ?>
The output of the above code will be:
Array ( [1] => John [value] => John [0] => name [key] => name )
Example: Traversing an array with each()
Consider one more example where each() function is used to traverse through a given array.
<?php $Arr = array("name"=>"John", "age"=>25, "city"=>"London"); reset($Arr); while (list($key, $val) = each($Arr)) { echo "$key => $val\n"; } ?>
The output of the above code will be:
name => John age => 25 city => London
❮ PHP Array Reference