I am trying to use session variables in an e-commerce website. The idea is to start a session if one is not started already. If there’s already a session, then i want to check if the new item that was added already exists in the session array. If so, then i’d just increase the quantity, if not then append to the current session array.
Problem is that appending does not work. I get the first and second arrays, but instead of adding a third the second array keeps getting overwritten anytime the add to cart button is clicked. Here is my code
<?php
if(isset($_SESSION['cart'])){
$newItems = '';
$cart = $_SESSION['cart'];
foreach($cart as $item => $value){
//$size, $colour, $quantity and $price are the current $_GET values
if($prodId == $value['prodId'] && $value['colour'] == $colour && $value['size'] == $size && $value['price'] == $price){
$value['qty']+= $quantity;
}else{
$newItems = array('prodId'=>$prodId,'price'=>$price,'qty'=>$quantity,'colour'=>$colour,'size'=>$size);
$cart []= $newItems;
}
}
}else{
$_SESSION['cart'] []= array('prodId'=>$prodId,'price'=>$price,'qty'=>$quantity,'colour'=>$colour,'size'=>$size);
}
?>
Really don’t know where it went wrong, i’ve such rotten luck with multidimensional arrays. Any help will be most appreciated.
You assigned
$_SESSION['cart']to a variable and then worked with that. This is only a copy and not a reference to your original variable. If you want to access your$_SESSIONagain and manipulate it, you can achieve this that way:— or —
You simply assign
$cartto$_SESSION['cart']again after manipulating$cart.