Wednesday, July 23, 2008

assigned by value?


$myArray = array('key1'=>array('1', '2'), 'key2'=>array('3', '4'));
$subArray = $myArray['key1'];
array_push($subArray, '5');

The trick is that new value '5' is ONLY added to $subArray, but not to $myArray['key']. PHP's assignment operator '=' assigns value by copy. So $subArray is not really a sub-array of $myArray, it is a separate array. Assignment by reference is also supported, using the $var = &$othervar; syntax.

The same for the 'foreach' loop

foreach($myArray as $subArray)

As of PHP 5, foreach ($arr as &$value) is supported. This will assign reference instead of copying the value.

No comments: