Possible Duplicate:
PHP Pass by reference in foreach
Why does the value change for both items in array? I’m just trying to change the value of the key that is equal to $testitem.
Desired result of following code:
item:5 Quantity:12
item:6 Quantity:2
The current result of the following code is:
item:5 Quantity:12
item:6 Quantity:12
<?php
$items = array(
'5' => '4',
'6' => '2',
);
$testitem = '5';
$testvalue = '8';
foreach($items as $key => &$value)
{
if ($key == $testitem)
{
$value = $value + $testvalue;
}
}
foreach($items as $key => $value)
{
print 'item:'.$key.' Quantity:'.$value.'<br/>';
}
?>
The problem comes when you attempted to pass the
$valuevariable as a reference. You will be able to achieve your desired result by modifying yourforeachloop to look like this –Simply use the current
$keyor the value of$testitemfor that matter, as a reference to your$itemsarray – and modify the contents like that.