Latest web development tutorials
 

PHP each() Function

< PHP Array Reference

Example

Return the current element key and value, and move the internal pointer forward:

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>
Run example »

Definition and Usage

The each() function returns the current element key and value, and moves the internal pointer forward.

This element key and value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key.

Related methods:

  • current() - returns the value of the current element in an array
  • end() - moves the internal pointer to, and outputs, the last element in the array
  • next() - moves the internal pointer to, and outputs, the next element in the array
  • prev() - moves the internal pointer to, and outputs, the previous element in the array
  • reset() - moves the internal pointer to the first element of the array

Syntax

each(array)

Parameter Description
array Required. Specifies the array to use

Technical Details

Return Value: Returns the current element key and value. This element key and value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key. This function returns FALSE if there are no more array elements
PHP Version: 4+

More Examples

Example 1

Same example as the one on top of the page, but with a loop to output the whole array:

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

reset($people);

while (list($key, $val) = each($people))
  {
  echo "$key => $val<br>";
  }
?>
Run example »

Example 2

A 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
?>
Run example »

< PHP Array Reference