Edit report at https://bugs.php.net/bug.php?id=64027&edit=1
ID: 64027
Comment by: matthew dot vince at gmail dot com
Reported by: mfuhrman at enetarch dot net
Summary: ForEach fails to add new key/value pairs
Status: Open
Type: Bug
Package: Scripting Engine problem
Operating System: Linux svm0907pdv 2.6.18-308.8.2.
PHP Version: 5.3Git-2013-01-18 (snap)
Block user comment: N
Private report: N
New Comment:
This is expected behavior. To modify values using a foreach loop, you need to
assign by reference, as explained in the foreach documentation:
foreach ($aryJunk AS &$sub)
$sub ["munch"] = "junk";
http://php.net/manual/en/control-structures.foreach.php
Previous Comments:
------------------------------------------------------------------------
[2013-01-18 20:13:51] mfuhrman at enetarch dot net
Description:
------------
using PHP Version 5.3.3, Build Date Jun 25 2012 04:51:11
In testing updating nested arrays, I'm finding the that the results of an array
is not updated, since the variable used to point to that portion of the array
seems to be a copy of the data and not a direct reference to the data.
Below is an array of arrays.
In the for loop, $sub points to $aryJunk's elements .. 0 .. 4 respectively.
When $sub has a new key value pair added, ex. "munch" => "junk", this value
only
exists as long as $sub exists in the for loop. Outside that loop, the key value
pair are lost.
It is my understanding that this key value pair should not be lost. Or, at
least I cannot find an example that says definitively one way or the other.
Please test to see if this issue still exists in the latest version of PHP, and
determine the next steps to resolution.
Michael J. Fuhrman
[email protected]
skype ENetArch
Test script:
---------------
$aryJunk = Array
(
0 => array(),
1 => array(),
2 => array(),
3 => array(),
4 => array(),
);
// fails
foreach ($aryJunk AS $sub)
$sub ["munch"] = "junk";
print_r ($aryJunk);
// works
for ($t=0; $t < count ($aryJunk); $t++)
$aryJunk[$t] ["munch"] = "junk";
print_r ($aryJunk);
Expected result:
----------------
Array ( [0] => Array ( [munch] => junk ) [1] => Array ( [munch] => junk ) [2]
=>
Array ( [munch] => junk ) [3] => Array ( [munch] => junk ) [4] => Array (
[munch]
=> junk ) )
Actual result:
--------------
Array ( [0] => Array ( ) [1] => Array ( ) [2] => Array ( ) [3] => Array ( ) [4]
=>
Array ( ) )
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=64027&edit=1