So I have a cart system that needs to update the quantity of a specific session variable. Right now if I have a item with the id = 1,

![enter image description here

and add another item with an id = 1, it updates the quantity to 2

enter image description here

, which is fine. But then if I add an item with id = 2,

enter image description here

and I again add another item with id = 1, it updates the quantity of id = 2 to 2,

enter image description here

when it should update the quantity of id = 1 to 3

enter image description here

Here's my code :

$exists = false;
foreach ($_SESSION['cart'] as $key => $item) {
    if ($item['product_id'] == $part_id) {
        $exists = true;
    }
}
if ($exists == true) {
    $_SESSION["cart"][$key]['quantity']++;
}
else{
$_SESSION['cart'][] = array(
    'product_id' => $part_id,
    'title' => $title,
    'price' => $price,
    'default_img' => $default_img,
    'quantity' => $quantity);
}

1 Answers

1
Nick On Best Solutions

At the end of your loop, when you update $_SESSION["cart"][$key]['quantity'], $key will always be pointing at the last item in $_SESSION["cart"], hence the behaviour you are seeing. You should either do the update in the loop e.g.

foreach ($_SESSION['cart'] as $key => $item) {
    if ($item['product_id'] == $part_id) {
        $exists = true;
        $_SESSION["cart"][$key]['quantity']++;
    }
}

or break from the loop when you find a match so that $key is pointing at the correct value:

foreach ($_SESSION['cart'] as $key => $item) {
    if ($item['product_id'] == $part_id) {
        $exists = true;
        break;
    }
}