PHP Why does the value change for both elements of the array?

Possible duplicate:
PHP Pass by reference in foreach

Why does the value change for both elements of the array? I'm just trying to change the value of a key equal to $ testitem.

Desired result of the following code: pcs: 5 Quantity: 12 item: 6 Quantity: 2

Current result of the following code: pcs: 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/>';
            }
?>
+5
source share
3 answers

The problem occurs when you try to pass a variable $valueas a reference. You can achieve the desired result by changing the cycle foreachto look like this:

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

$key $testitem, , $items - , .

+8

Becouse $ foreach.

unset($value), , foreach .

0

Why don't you just use this code instead of a loop:

$ items [$ testitem] + = $ testvalue;

This works for your example.

In php, you can reference an array element with a variable. So he definitely does what you want.

-2
source

All Articles