I have struggled to find a solution to a simple shopping cart with $_SESSION
.
I kept it very simple and this is my code right now
if ( Input::isPost('add') ) {
$id = Input::get('id');
$qta = Input::post('qta');
$size = Input::post('size');
if ( !isset($_SESSION['cart']) ) {
$_SESSION['cart'] = array();
}
if ( array_key_exists($id, $_SESSION['cart']) ) {
if ( $_SESSION['cart'][$id][0] == $size ) {
$_SESSION['cart'][$id][1]+=$qta;
} else {
$_SESSION['cart'][$id] = array( $size, $qta );
}
} else {
$_SESSION['cart'][$id] = array( $size, $qta );
}
}
So, what this code does ?
1) If the $_SESSION['cart']
does not exist, create it, otherwise add the new item. 2)When you add to cart a item, you must choose a size and a quantity for that item. 3) If that item already exists in the cart array, check if the size is the same, if so just update the quantity. Here is the problem, if the item already exists(checks for the $_SESSION['cart'][$id]
) BUT the size is different, do not update the current one, but instead create a new item. The problem is that the current one is being replaced instead of adding one, so instead of 2 products with the same id
but different size
, I only have the most recent one.
If you could help me solve it I'll be very thankful !
Thank you in advance.