|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2009-05-27 12:57 UTC] jani@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Dec 04 20:00:01 2025 UTC |
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 ) )