PHP - Why does the value change for both items in array?

arrays, php

Solution

The problem comes when you attempted to pass the `$value` variable as a reference. You will be able to achieve your desired result by modifying your `foreach` loop to look like this -

foreach($items as $key => $value){   
  if ($key == $testitem){
    $items[$key] = $value + $testvalue;   
  }
}

Simply use the current `$key` or the value of `$testitem` for that matter, as a reference to your `$items` array - and modify the contents like that.

Problem

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/>'; } ?> ```

Original source

Related problems