I am working on a function that adds an item to a cart. If the item already exists in the cart, increase its quantity amount by 1. If it doesn't, I want to add the item array in the next position in the cart array. Here's my code that I am using where $add_to_cart is the item ID:
if ($add_to_cart) {
$added = false;
foreach ($cart as &$item){
if ($item['id'] == $add_to_cart){
$item['qty'] += 1;
$added = true;
}
}
if (!$added) {
$cart[count($cart)]['id'] = $add_to_cart;
$cart[count($cart)]['qty'] = 1;
}
$_SESSION[$session_id]['cart'] = $cart;
}
When I use this code, it appends the ID of the item as the second last element, then the qty value as the last element. How can I make this work?