php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #77014 Array traversal issues PHP 7+
Submitted: 2018-10-15 15:09 UTC Modified: 2019-07-12 15:55 UTC
From: mishamosher at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 7.2.11 OS:
Private report: No CVE-ID: None
 [2018-10-15 15:09 UTC] mishamosher at gmail dot com
Description:
------------
There is a different behaviour between PHP 5.x and 7.x when traversing arrays.

I can not find if this is intended, so I'm supposing its a bug.

Test script:
---------------
https://3v4l.org/YNJ18

Expected result:
----------------
I expect the same output on PHP 5.x and 7.x.

Actual result:
--------------
The outputs differ between PHP 5.x and 7.x.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-11-26 14:34 UTC] george dot banyard at gmail dot com
I don't think this is a bug with the array traversal but more with the copying of the array state when the function is executed.
If you reverse the order of execution as shown here: https://3v4l.org/l1bYA

You get the same result in PHP5.x and 7.x

Only difference that I know of is that before PHP7 foreach would use the internal pointer of the array which isn't necessary any more.

So maybe there was a pointer reset mechanism for all loops which has been removed during the transition from 5 to 7.

Also I do think the new behaviour in this case is Intended and wouldn't considered it a bug.
 [2019-07-12 15:16 UTC] mishamosher at gmail dot com
Bump. Can anyone from the PHP team confirm if this behaviour is intended or if it is a bug?
 [2019-07-12 15:34 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2019-07-12 15:34 UTC] nikic@php.net
The behavior is intended. Passing an array to a function does not change the position of the internal array pointer. I believe the PHP 5 behavior was some kind of artifact of key() accepting the array by reference and triggering a separation there.

If you'd like to make sure that you are iterating the array from the start rather than from the previous position of the internal array pointer, you can perform an explicit call to reset().

(I'd recommend moving away from these functions entirely, if it is at all possible. If complex iteration patterns are involved, ArrayIterator may be an alternative.)
 [2019-07-12 15:55 UTC] mishamosher at gmail dot com
Thank you nikic for the information (:
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Tue Mar 31 20:01:24 2020 UTC