0

I get this message on a theme that I am using with my opencart 2.3.0.2: Unknown: The each() function is deprecated. This message will be suppressed on further calls in /..../Number.php on line 293

This is what is writen on that line in that php file:

reset($units);
list($unit, ) = each($units);

return (string) $dimension . $unit;
}

I already understand it has to do with the PHP version, which is set at 7.2 (can't set it to older versions) and the part of 'each' should be rewriten to 'foreach', but I can't figure out how to do that correctly in this situation... Can anybody help?

Pamvz
  • 9
  • 2
  • This particular use of `each` can probably simply be replaced by `$unit = key($units)`. Both return the current key in the array, but `each` also returns the value and advances the array pointer, which seems irrelevant here. – deceze Jan 06 '21 at 11:36

1 Answers1

1

each() has been officially deprecated in PHP 7.2 but it is out of fashion since PHP 4 (i.e. since about 20 years ago).

It returns an array containing at position 0 the key and at position 1 the value of the current element of the array passed to it as argument and advances the internal array pointer to the next element. Its behaviour can be confusing, this is why foreach() (or another way to iterate over the array) is preferred to be used instead.

Your code:

reset($units);
list($unit, ) = each($units);

reset($units) moves the internal pointer of the $units array to its first element. Then each($units) returns the key and the value of the first element (and advances to the next element but this is not important for the rest of the code).

list($unit, ) copies in $unit the first value from the array (of two values) returned by each($units) and ignores the second value.

All in all, the code above puts in $unit the key of the first element of the array (the first key of the array).
There are several ways to achieve the same result without each().

One of them is to use array_keys() to get all the keys then get the first of them using the usual array indexing with [0]:

$unit = array_keys($units)[0];

Or you can use reset() to move the internal array pointer to its first element then key() to get the key of the current element.

reset($units);
$unit = key($units);

However I do not recommend relying on the internal pointer of the array. It works fine but the code that uses it can easily introduce hidden bugs.

Since PHP 7.3 you can use the function array_key_first() that produces the same result as the code above but it is faster:

$unit = array_key_first($units);
axiac
  • 68,258
  • 9
  • 99
  • 134