
Time to write something about PHP again. With PHP 7.2, the function each
() is deprecated. The documentation says: “Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.“.
If you ignored this warning before, in PHP8 you will now get the following error: Fatal error: Uncaught Error: Call to undefined function each() in /path/file.php:line
So, what do you do when you find this in your old code or in some library that you use, but is not being updated anymore? Stackoverflow to the rescue…
I already knew this one, in the while loop:
while (list($key, $arg) = each($args)) {
Just change that into a foreach loop:
foreach ($args as $key => $arg) {
But what if you find the following in your code? list/each on a single line, simply means the function is only executed once of the current index, instead of looping through the whole array. So see this:
list($key, $arg) = each($args);
Well, simply use the functions key() and current() to replace that one:
$key = key($args);
$arg = current($args);
Find more constructions and solutions on stackoverflow. Unfortunately I did not find the following combined expression of a simple evaluation and the list/each construction:
while ($a > $b && list($key, $arg) = each($args)) {
...
But I solved it like this:
foreach($args as $key=> $arg) {
if (!($a > $b)) {
break;
}
...
But wait, there is more!
I also found a simple one…
$element = each($arr);
If I read stack correctly:
$key = key($arr);
$result = ($key === null) ? false : [$key, current($arr), ‘key’ => $key, ‘value’ => current($arr)];
That code should be changed into this:
$element = [key($arr), current($arr), 'key' => key($arr), 'value' => current($arr)];
That’s all folks!
Have a nice day…