php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #41603 foreach not manipulating last element when passed by reference
Submitted: 2007-06-05 22:12 UTC Modified: 2007-06-06 22:29 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: david at terrainferno dot net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.3 OS: Windows XP
Private report: No CVE-ID: None
 [2007-06-05 22:12 UTC] david at terrainferno dot net
Description:
------------
This was reported in 2006 in the foreach user comment http://uk.php.net/manual/en/control-structures.foreach.php#60806, but using php5 using references in a foreach loop, manipulating the last element in an array seems to have no effect, the reference is referred to as $v.

Reproduce code:
---------------
// fails to work as expected
$ar = array(1,2,3,4);

foreach ($ar as &$v){
    $v *= 2;
}
foreach($ar as $v){
    echo $v . '<br>';
}

// works correctly
$ar = array(1,2,3,4);

foreach ($ar as &$o){
    $o *= 2;
}
foreach($ar as $o){
    echo $o . '<br>';
}

Expected result:
----------------
2
4
6
8

Actual result:
--------------
2
4
6
6

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-06-06 04:28 UTC] judas dot iscariote at gmail dot com
This is the expected beahviuor, this issue has been reported counteless of time, and explained to death.

for an explanation see comment by gardan at gmx dot de here:

http://bugs.php.net/bug.php?id=29992


I wonder why does not raise an E_NOTICE "shooting yourself in the foot with references" :-)
 [2007-06-06 06:15 UTC] tony2001@php.net
Please search the database before reporting.
 [2007-06-06 07:19 UTC] david at terrainferno dot net
How could this possibly be expected behaviour. This isnt a feature that happens every time and can be explained away (I would understand if this was some bizarre feature of referencing arrays), as shown by the 2 test cases provided, they are identical apart from the name given to the reference variable, just changing the name changes the result, how can this possibly be expected behaviour???
 [2007-06-06 08:16 UTC] tony2001@php.net
Read detailed explanation here: http://bugs.php.net/bug.php?id=29992
BOTH your examples work the very same way and produce the very same result.
 [2007-06-06 22:29 UTC] david at terrainferno dot net
Appologies, I can now see how the behavior is occuring. Thanks for point ing me in the right direction.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu May 02 20:01:31 2024 UTC