php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #54321 Foreach not running through added elements when passed by reference
Submitted: 2011-03-20 13:45 UTC Modified: 2011-04-12 20:27 UTC
From: unokpasabaxaki at yahoo dot es Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 5.2.17 OS:
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: unokpasabaxaki at yahoo dot es
New email:
PHP Version: OS:

 

 [2011-03-20 13:45 UTC] unokpasabaxaki at yahoo dot es
Description:
------------
I found out that foreach sometimes doesn't run through elements added to an array 
when the value is passed by reference. I haven't tested enough to say it for sure, 
but I think it happens only on elements added on what would be the last iteration 
of foreach.

Test script:
---------------
$array = array('a', 'b', 'c');
foreach ($array as $i => &$val) {
   echo $val.' ';
   if ($i % 2 == 1) $array[] = $val.'2';
}

Expected result:
----------------
When it reaches $array[1] (b), it creates $array[3] with the value "b2". Then it 
runs through $array[3] and creates $array[4] with the value "b22". After that, it 
should run through $array[4] too, outputting altogether "a b c b2 b22" and 
stopping.

Actual result:
--------------
Since at the start of the iteration, $array[3] is the last element of the array, 
after $array[4] is created in that iteration, it doesn't run through it, 
outputting just "a b c b2". Still, $array[4] is created.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-04-12 20:27 UTC] iliaa@php.net
-Status: Open +Status: Bogus
 [2011-04-12 20:27 UTC] iliaa@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

foreach makes a copy of the array to run through, any changes to that array within 
the scope of foreach() construct are not visible to it.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC