Sohail Malik
Sohail Malik

Reputation: 335

Multidimensional array in php SESSION

I am having problem with updating an array element with in $_SESSION variable of PHP. This is the basic structure:

$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;

And then by using array_push() function I insert that product in SESSION variable.

array_push($_SESSION['cart'], $product); 

Now this is the main part where i m facing problem:

foreach($_SESSION['cart'] as $product){

    if($id == $product['id']){
        $quantity = $product['quantity'];
        $quantity += 1;
        $product['quantity'] = $quantity;       
    }

}

I want to increment product quantity within $_SESSION['cart'] variable. How can I do that?

Upvotes: 5

Views: 35791

Answers (3)

Youssef
Youssef

Reputation: 191

I faced the same issue before, and the accepted answer works only because it modifies the session variable directly, but in a foreach loop, you must pass the $product variable by reference (by prepending & to it) to be able to save changes like this :

foreach($_SESSION['cart'] as &$product){
    if($id == $product['id']){
        $product['quantity'] += 1;
    }
}

Or if you follow the accepted solution :

foreach($_SESSION['cart'] as $id => &$product){
    if($searchId == $id){
        $product['quantity'] += 1;
    }
}

Upvotes: 1

Budi Liauw
Budi Liauw

Reputation: 29

this not best answers for u...but hope can help u guys im not expert coders, and just learn coding in this forum ^,^ .You must always trying to solved. for more example hope can help to update value quantity:

<?php 
if(isset($_POST['test'])) {
    $id =$_POST['id'];

    $newitem = array(
    'idproduk' => $id, 
    'nm_produk' => 'hoodie', 
    'img_produk' => 'images/produk/hodie.jpg', 
    'harga_produk' => '20', 
    'qty' => '2' 
    );
    //if not empty
    if(!empty($_SESSION['cart']))
    {    
        //and if session cart same 
        if(isset($_SESSION['cart'][$id]) == $id) {
            $_SESSION['cart'][$id]['qty']++;
        } else { 
            //if not same put new storing
            $_SESSION['cart'][$id] = $newitem;
        }
    } else  {
        $_SESSION['cart'] = array();
        $_SESSION['cart'][$id] = $newitem;
    }
} 
?>
<form method="post">
<input type="text" name="id" value="1">
<input type="submit" name="test" value="test">
<input type="submit" name="unset" value="unset">
</form>

Upvotes: 2

Marc B
Marc B

Reputation: 360882

Don't blindly stuff the product into your session. Use the product's ID as the key, then it's trivial to find/manipulate that item in the cart:

$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = array('type' => 'foo', 'quantity' => 42);

$_SESSION['cart'][$id]['quantity']++; // another of this item to the cart
unset($_SESSION['cart'][$id]); //remove the item from the cart

Upvotes: 17

Related Questions