Have you tried using this?
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = $item;
You don't need to serialize the item-variable - a Session can store pure Objects, as long as the max. session-size doesn't exceed.
If you want to remove Items from the cart, you should use index-Names - this allows you to find your items faster.
I would probably use something like this:
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
function addItem($itemName){
if(!isset($_SESSION['cart'][$itemName])) {
$_SESSION['cart'][$itemName] = 1;
}else
$_SESSION['cart'][$itemName] ++;
}
}
function removeItem($itemName){
if(isset($_SESSION['cart'][$itemName])) {
if($_SESSION['cart'][$itemName] > 0) {
$_SESSION['cart'][$itemName] --;
}
}
}
function clearCart(){
unset($_SESSION['cart']);
}
In this case, the cart stores each item and its amount. Instead of $itemName, you could also use the item-ID from your database.
To get an item from the cart, you will need this function:
function getItemCount($itemName){
if(isset($_SESSION['cart'][$itemName])) {
return $_SESSION['cart'][$itemName];
}
return 0;
}