#48404 [Opn->Bgs]: Passing variables byRef to foreach and doing array_reverse yelds unexp. results
| From: | jani@php.net | Date: | Wed, 27 May 2009 12:57:36 +0000 |
| Subject: | #48404 [Opn->Bgs]: Passing variables byRef to foreach and doing array_reverse yelds unexp. results | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-137776@lists.php.net to get a copy of this message | ||
ID: 48404
Updated by: jani@php.net
Reported By: praxodas at gmail dot com
-Status: Open
+Status: Bogus
Bug Type: Scripting Engine problem
Operating System: linux
PHP Version: 5.2.9
New Comment:
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
Previous Comments:
------------------------------------------------------------------------
[2009-05-27 10:29:46] 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
)
)
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=48404&edit=1