PHP Array iteration Using internal array pointers


Each array instance contains an internal pointer. By manipulating this pointer, different elements of an array can be retrieved from the same call at different times.

Using each

Each call to each() returns the key and value of the current array element, and increments the internal array pointer.

$array = ["f" => "foo", "b" => "bar"];
while (list($key, $value) = each($array)) {
    echo "$value begins with $key";

Using next

$array = ["Alpha", "Beta", "Gamma", "Delta"];
while (($value = next($array)) !== false) {
    echo "$value\n";

Note that this example assumes no elements in the array are identical to boolean false. To prevent such assumption, use key to check if the internal pointer has reached the end of the array:

$array = ["Alpha", "Beta", "Gamma", "Delta"];
while (key($array) !== null) {
    echo current($array) . PHP_EOL;

This also facilitates iterating an array without a direct loop:

class ColorPicker {
    private $colors = ["#FF0064", "#0064FF", "#64FF00", "#FF6400", "#00FF64", "#6400FF"];
    public function nextColor() : string {
        $result = next($colors);
        // if end of array reached
        if (key($colors) === null) {
        return $result;