Forum Moderators: coopster

Message Too Old, No Replies

each() is deprecated in PHP 7.x, best alternative?

         

csdude55

4:24 am on Jul 24, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've discovered that this:

$array['one'] = 'a';
$array['two'] = 'b';
$array['three'] = 'c';
$array['four'] = 'd';
$array['five'] = 'e';

// 0.00085210800170898s
while (list($key, $val) = each($array))
$$key = $val;

is about twice as fast as this (tested over 10,000 iterations):

// 0.0017039775848389s
foreach ($array as $key => $val)
$$key = $val;

But with each() being deprecated in PHP 7.2, is there a replacement that's just as fast or faster? Or do I just have to stick with the slower foreach?

w3dk

6:07 pm on Jul 29, 2020 (gmt 0)

10+ Year Member Top Contributors Of The Month



Ironically, one of the given reasons why each() is deprecated is that it's "far slower at iteration than a normal foreach"!

Reference: [php.net...]

each() function
This function is far slower at iteration than a normal foreach, and causes implementation issues for some language changes. It has therefore been deprecated.



...is about twice as fast as this...


Although, depending on how you've implemented the "10,000 iterations", the two code samples you've posted aren't necessarily doing the same thing. When using each() you need to reset the internal array pointer at the start of each loop, otherwise it's only going to traverse the array at most once. Whereas foreach() automatically resets the internal array pointer (on PHP7 it doesn't use the internal array pointer).

FWIW, I just tried the same tests (but resetting the array pointer with each() to create a comparable test) and I'm finding foreach() to be on average 5x (500%) quicker! (In fact, I had to increase the number of iterations with the foreach() method since 10,000 was finishing too quickly to measure!)

Aside: Your code creates variables in the current scope from elements of an array - there is already a built-in PHP function to do this. See extract() - [php.net...]

csdude55

9:12 pm on Jul 29, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I think you're right, not resetting it made it run faster... but might not have been accurate results. I'm not sure that using reset() would have made a difference in my live code, but it might have so I would still probably have needed it.

Here's my original test, without using reset():

[sandbox.onlinephpfunctions.com...]

while: 0.00077199935913086
foreach: 0.0015859603881836
extract: 0.0011110305786133

But then WITH reset():

[sandbox.onlinephpfunctions.com...]

while: 0.01070499420166
foreach: 0.0017480850219727
extract: 0.0012068748474121

So yeah, now it looks like extract() is the fastest, but only marginally faster than foreach().