Fallback for PHP's each function

The each function or each() function has been deprecated as of PHP 7.2.0, and was completely removed as of PHP 8.0.0. Using this function on 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 you don't have time to go through all the lines of codes to replace them, you can simply create a global function to substitute for the undefined each function.

To create a fallback each function, create a function called "each" and replicate the process of the original. As per PHP Manual, each returns the current key and value pair from an array and advance the array cursor. Our fallback each function should be instructed to do exactly like that.

Now, there are many ways to achieve this function, but one way to do this is to code it like this:

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 on each() is passed by reference, meaning, the array going through our function is processed as it passes and does not need to be stored in another array variable.

Explanation

On line 2 of our code, our process starts by retrieving the key value of our array, ie. if we have an array containing ['fruit' => 'watermelon'], our key would be "fruit".

Line 3 checks our key. If key is null then our function would return a false (bool) value, but if it's not null, then it would return an array that contains the key and the current array value. Note that "current" function returns the first value in an array so let's say we have an array containing ['apple','melon','grapes'], we would get "apple" with the current() function.

Line 5 uses the next() function, this function moves the internal pointer of an array to the next value. For example, if we have an array ['banana','jack fruit','coconut'], this function would give us "jack fruit". Since our array is passed by reference, next() function's effect would be applied to the array even without returning it. Thus, achieving each()'s final function, which is to advance the array cursor.

Finally, line 6 returns our result, which can be either false or an array containing the current key and value pair of the array. This does each()'s initial function.

Leave a Reply

Your email address will not be published. Required fields are marked *