php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51049 Last Array Element Replaced by Second Last one
Submitted: 2010-02-15 04:47 UTC Modified: 2010-02-15 05:05 UTC
From: timminn at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.3.1 OS: Arch Linux 2.6.31
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: timminn at gmail dot com
New email:
PHP Version: OS:

 

 [2010-02-15 04:47 UTC] timminn at gmail dot com
Description:
------------
if AN ARRAY WITHIN AN OBJECT is used in "a straight manner" in the foreach() loop,  with the references to its values[poor English, see the SECOND foreach() in the submitted code to understand I mean],

the last value in the array will be REPACED with the second last one ACCIDENTALLY, WITHOUT ANY ASSIGNMENT OPERATION.



Reproduce code:
---------------
<?php
    class myc{  public $a;  }
    $o3->a  =  Array(  11,  22  );

    //loop ONE
    foreach(  $o3->a  as  $k =>  $v  )
        echo $v. ' ';     //EXPECT 11 22 ,  CORRECT OUTPUT
    echo "\n=========\n";

    //loop TWO notice the reference & sign for $v
    foreach(  $o3->a  as  $k => & $v  )
        echo $v. ' ';    //EXPECT 11 22 ,  CORRECT OUTPUT
    echo "\n=========\n";

    //loop THREE
    foreach(  $o3->a  as  $k => $v  )
        echo $v. ' ';    //EXPECT 11 22 , BUT WRONG OUTPUT: 11 11
    echo "\n=========\n";
?>

Expected result:
----------------
11 22
11 22
11 22

Actual result:
--------------
11 22
11 22
11 11

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-02-15 05:03 UTC] timminn at gmail dot com
the bug occurs ONLY WHEN:
MUST BE used in a STRAIGHT MANNER as ARRAY IN OBJECT, as shown in the sbmitted code,

in other words, if we use
$sa  =  $o3->a;
and foreach( $sa as $k => & $v ){ ... }
the bug will not occur
 [2010-02-15 05:05 UTC] aharvey@php.net
Reusing a variable that you've used to hold value references in a 
foreach loop leads to Bad Things?. That's why the manual page for 
foreach has a big red box recommending that you unset() the variable 
after you're done with the loop.

Recent bugs dealing with this include bug #50485, bug #50582 and bug 
#48561. This behaviour isn't going to be changed as it would break 
backward compatibility.

Closing.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 09 23:01:33 2025 UTC