next

next($array)

Moves the internal array pointer one element forward and returns the value of the element it stopped at. When there is no next element, it returns false.

Parameters

  • $array – the array. It must be a variable.

Examples

$array = array("a", "b", "c");
// it returns the following element, not the current one
echo next($array); // b
echo next($array); // c
// there is no next element
var_dump(next($array)); // bool(false)
// the pointer stays past the end, reset moves it back to the start
var_dump(current($array)); // bool(false)
echo reset($array); // a
// walking from the first element: current first, then next
$output = "";
for ($value = current($array); key($array) !== null; $value = next($array)) {
  $output .= $value;
}
echo $output; // abc
// an element with the value false ends a loop with a condition on false too early
$values = array(1, false, 3);
$count = 1;
while (next($values) !== false) {
  $count++;
}
echo $count; // 1

Things to watch out for

  • It returns the value of the next element. So you never get the first element of the array through next, that one is returned by current() or reset().
  • The return value false means the end of the array, but an element with the value false looks the same. The end is reliably detected by key() returning null.
  • Once the pointer runs past the end of the array, prev() does not bring it back. Only reset() or end() helps.
  • The parameter must be a variable. In new code use a foreach loop to walk through an array.

Related functions:
prev()
current()
reset()