php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #48404 Passing variables byRef to foreach and doing array_reverse yelds unexp. results
Submitted: 2009-05-27 10:29 UTC Modified: 2009-05-27 12:57 UTC
From: praxodas at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.9 OS: linux
Private report: No CVE-ID: None
 [2009-05-27 10:29 UTC] praxodas at gmail dot com
Description:
------------
After reversing an array and passing it by reference in foreach and then doing array_reverse on itself, passing the same array by value in another foreach overwrites previous array elements with the last one.

If a copy of an array is made, the copy is overwritten as well.

A workaround would be to pass the array by reference in the next foreach loop.



Reproduce code:
---------------
<?php
$demo_array=array(array('val1'=>'apple', 'ord_num'=>2),array('val2'=>'orange', 'ord_num'=>3));
$demo_array=array_reverse($demo_array);
foreach ($demo_array as $key=>&$el)
{
        $el['ord_num']=$key;
}
$demo_array=array_reverse($demo_array);
$new_array=$demo_array;
        foreach ($demo_array as $k=>$el)
        {
         // do nothing,..
        }
echo "\r\nnew_array:\r\n";
print_r($new_array);
echo "\r\ndemo_array:\r\n";
print_r($demo_array);

?>


Expected result:
----------------
new_array:
Array
(
    [0] => Array
        (
            [val1] => apple
            [ord_num] => 1
        )

    [1] => Array
        (
            [val2] => orange
            [ord_num] => 0
        )

)

demo_array:
Array
(
    [0] => Array
        (
            [val1] => apple
            [ord_num] => 1
        )

    [1] => Array
        (
            [val2] => orange
            [ord_num] => 0
        )

)


Actual result:
--------------
new_array:
Array
(
    [0] => Array
        (
            [val2] => orange
            [ord_num] => 0
        )

    [1] => Array
        (
            [val2] => orange
            [ord_num] => 0
        )

)

demo_array:
Array
(
    [0] => Array
        (
            [val2] => orange
            [ord_num] => 0
        )

    [1] => Array
        (
            [val2] => orange
            [ord_num] => 0
        )

)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-05-27 12:57 UTC] jani@php.net
RTFM: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). 

Mentioned in the fine manual at: http://php.net/foreach

 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Dec 04 19:00:01 2025 UTC