Using internal array pointers
suggest changeEach 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.
Reading the current key and value
The each() function was removed in PHP 8. Use key(), current(), and next() when direct control of the internal array pointer is required:
$array = ["f" => "foo", "b" => "bar"];
reset($array);
while (($key = key($array)) !== null) {
$value = current($array);
echo "$value begins with $key";
next($array);
}
Using next
$array = ["Alpha", "Beta", "Gamma", "Delta"];
while (($value = next($array)) !== false) {
echo "$value\n";
}
The pointer starts on the first element, so the first next() returns Beta and Alpha is skipped.
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;
next($array);
}
This also facilitates iterating an array without a direct loop:
class ColorPicker {
private array $colors = ["#FF0064", "#0064FF", "#64FF00", "#FF6400", "#00FF64", "#6400FF"];
public function nextColor(): string {
$result = next($this->colors);
// if end of array reached
if (key($this->colors) === null) {
$result = reset($this->colors);
}
return $result;
}
}
The pointer starts on the first color, so the first call returns the second color. The first color is returned only after the pointer wraps.