Today I am working on the shopping cart for a users website script. When they add an item to the cart, it is stored in a $_SESSION
variable called cartitems
. I am storing arrays within the array of $_SESSION['cartitems']
that contain the item's itemid
and the quantity of the items they are trying to add to the cart. Simply adding the items works awesome using the code I list below this, but I need them to increase the value of the items in the array assuming they try and add more of the same item instead of simply adding a new array into the SESSION. Heres an example:
-> User 1 visits the website.
- Add 5 melons to cart.
- Add 3 lemons to cart.
- Add 2 more melons to cart.
My array would print something like:
array(
array{0 => 1, 1 => 5},
array{0 => 2, 1 => 3},
array{0 => 1, 1 => 2}
)
.. while the goal of adding them would be something instead like the following:
array(
array{0 => 1, 1 => 7},
array{0 => 2, 1 => 3}
)
So that the value on the itemid of 1 would be increased to 7. I also need to know what its at, before adding the extra 2, incase there is only 6 melons in stock. Wouldn't want someone finding a way to add more melons then there are left in the stock field now would we!
I am already passing the stock field amount, along with weather it has unlimited stock support, or buy limits on an item, so I have all the information I need to limit stuff (which I already do when adding the items), just need a way to change the array if its already in there to increase the number is all. Here's the code I use to add items:
if(isset($_POST['quantity'])) {
// Cast quantity to an int for protection
$quantity = (int) $_POST['quantity'];
if(!empty($quantity) && $quantity > 0) {
$errors = 0;
// It doesn't support unlimited stock so we check stock level
if($unlimstock == "0") {
if($quantity > $stock) {
$quantity = $stock;
}
if($buylimit > 0) {
if($quantity > $buylimit) {
$errors = "1";
}
}
}
if($errors == 0) {
$_SESSION['cartitems'][] = array($itemid, $quantity);
header("Location: cart.php");
die();
}
}
}
What is the best approach to check if it's in the array, if it is increase the value, if not I can add it like I am already, and if it is, what is the value so I know how much it can be increased by. Thanks guys!