What is the fallback for PHP’s each() function?

The each() function was deprecated in PHP 7.2.0 and completely removed in PHP 8.0.0. Using this function in your PHP code will trigger a “Call to undefined function” error when running on a PHP 8 server.

If you have a large system and don’t have the time to go through every line of code to replace all usages, you can create a global fallback function to substitute for the missing each() function.

To create a fallback for each(), define a function named each that replicates the behavior of the original function. According to the PHP Manual, each() returns the current key and value pair from an array and then advances the array pointer. Your fallback function should replicate this behavior exactly.

There are multiple ways to implement this fallback function. One approach is to code it as follows:

if (!function_exists('each')) {
  function each(&$array) {
    $key = key($array);
    $result = ($key === null) ? false :
              [$key, current($array), 'key' => $key, 'value' => current($array)];
    next($array);
    return $result;
  }
}

Note that the array passed to each() is passed by reference. This means the array is processed directly within the function, and there is no need to store it in another variable to preserve changes to the internal pointer.

Explanation

On line 3, the process begins by retrieving the current key of the array. For example, if the array contains ['fruit' => 'watermelon'], the retrieved key would be "fruit".

On line 4-5, the key is evaluated. If the key is null, the function returns false. If it is not null, the function prepares an array containing the current key and value pair. Note that the current() function returns the value at the current internal pointer position. For example, given an array ['apple', 'melon', 'grapes'], calling current() would return "apple".

On line 6, the next() function is called. This function advances the array’s internal pointer to the next element. For instance, if the array contains ['banana', 'jack fruit', 'coconut'], calling next() would move the pointer to "jack fruit". Because the array is passed by reference, this pointer movement affects the original array without needing to return it. This behavior replicates each()’s final responsibility: advancing the array cursor.

Finally, on line 7, the function returns the result. This will either be false (when the array has been fully traversed) or an array containing the current key and value pair. This fulfills each()’s primary purpose of returning the current element while advancing the pointer.

Leave a Reply