Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

php - Unknown: The each() function is deprecated on my Opencart Theme

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...