如何更改会话数组变量值

I have an array of 'products' in my session, a product is an array of name, code and quantity, I want to change the quantity when I press a 'qty_up' button:

my PHP is this:

if ($_POST['qty_up']==''){
    foreach ($_SESSION["products"] as $key => $val)
    {
        if ($val["product_code"] == $_POST['code']) {
            $val["product_qty"] += 1;
        }
    }
}

This changes $val["product_qty"] but not the real value in the session

This is my 'products' array in the session:

array (size=1)
  'products' => 
    array (size=5)
      213453 => 
        array (size=5)
          'product_qty' => string '1' (length=1)
          'product_code' => string '213453' (length=6)
          'product_name' => string 'Kingfisher' (length=10)
          'product_price' => string '12.00' (length=5)
      48754 => 
        array (size=5)
          'product_qty' => string '1' (length=1)
          'product_code' => string '48754' (length=5)
          'product_name' => string 'Minute maid' (length=11)
          'product_price' => string '2.00' (length=4)
      '3545231ES0' => 
        array (size=5)
          'product_qty' => string '1' (length=1)
          'product_code' => string '3545231ES0' (length=10)
          'product_name' => string 'Jagurt' (length=6)
          'product_price' => string '1.00' (length=4)

What's the need of this $val? You could directly update the session value.

if ($_POST['qty_up']=='') {

   foreach ($_SESSION["products"] as $key => &$val) {

       if ($val["product_code"] == $_POST['code']) {
           //$val["product_qty"] += $val["product_qty"];
           $_SESSION["products"][$key]['product_qty'] +=  $val["product_qty"]; // Add this
       }

    }
}

You can update the session value like below

if (isset($_SESSION['some_session_var'])) {
    $_SESSION['some_session_var'] = $udpated_value; //$udpated_value can you be your modified value.
}

Also, you first need to fetch the value from session variable, perform your add calculation and then update it.

You need to update $_SESSION not the local one, if you want to update using the local variable the you need to use & which is reference by value.

$_SESSION['products']["product_qty"] += $val["product_qty"];

in usual way foreach($products as $value) foreach walk through $products and assign every element to variable $value in each loop, its a copy of element value, so in your case change $val will not change $_SESSION

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Edit your code snippets like below:

foreach ($_SESSION["products"] as &$val)
{
    if ($val["product_code"] == $_POST['code']) {
        $val["product_qty"] += $val["product_qty"];
    }
}

If you feel confuse, read php official manual, it explain this behavior well. http://php.net/manual/en/control-structures.foreach.php

$_SESSION["products"][product_code to update]["product_qty"]=new value