Hey guys, check out this code:
<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 1 (if user attempts to add something to the cart from the product page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $pid) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
}
header("location: cart.php");
exit();
}
?>
I got this from an online tutorial and although I am not familiar with many of the php array manipulation functions, I got suspicious when I saw how the variable “i” was used in the arraysplice method.
I may be completely wrong but surely if you add one item to a cart first i stays as 0 because it is postfix. Then you add another “1” then you add a third so “i” is 2. If you then add a fourth item which happens to be a duplicate of the first then you want to replace the first array item quantity. Surely “i” is then 2-1 =1 which gives us the wrong index- we want [0] to replace the first item. This only seems to allow for a situation when the item and the duplicate item are next to one another and sure enough my script is crashing. Can anyone help?
Thanks
Will