2

I have been going through the entire documentation and stackoverflow Q&A and couldn't find any answer for this. In php, are these two while the exact same or are there differences between them. And if so, which?

while (list($key, ) = each($array))

and

while (list($key) = each($array))

I know I can convert the first to

foreach (array_keys($array) as $key)

But can I do the same conversion to while (list($key) = each($array))?

6
  • 2
    The each() function is deprecated and will be removed in a future PHP version. Commented Jul 14, 2018 at 11:24
  • 1
    Having said that, a quick test script seems to indicate that the second while-loop does exactly the same thing as the first, so you could use the same solution. Commented Jul 14, 2018 at 11:28
  • 1
    Thanks, @rickdenhaan. The reason I am asking is exactly because each is deprecated and I am adapting the script to php 7.2, and thus don't want to make any mistakes while adapting the code to use foreach. Commented Jul 14, 2018 at 11:32
  • @rickdenhaan, off-topic, but isn't it odd that your script take 14ms on php 5.6.30 and 23ms (almost double time) on php 7.2.7? Commented Jul 14, 2018 at 11:44
  • 1
    Not particularly. The array in that test script only contains 5 items, with that small a sample the script's runtime is heavily influenced by other system resource usage. I just tried running the same script with an array that has 100.000 items in it, that took 313 ms on PHP 5.6 and 110 ms on PHP 7.2. Commented Jul 14, 2018 at 11:55

1 Answer 1

4

Thanks to @rickdenhaan for his test script that shows they are identical, I wanted to point out that there is 1 more way to convert while (list($key, ) = each($array)):

foreach ($array as $key => $value)

Examples: https://3v4l.org/NV8MD

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.