0

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!

2 Answers 2

1

To simplify code your $_SESSION['cartitems'] should store data as:

$_SESSION['cartitems'] = [
    'product_id1' => 'quantity1',
    'product_id2' => 'quantity2',
];

Then updating a quantity is:

if (isset($_SESSION['cartitems'][$product_id])) {
    $_SESSION['cartitems'][$product_id] += $quantity;
} else {
    $_SESSION['cartitems'][$product_id] = $quantity;
}

If changing $_SESSION['cartitems'] structure is not possible, then you have to iterate over it:

$found = false;
foreach ($_SESSION['cartitems'] as $key => $item) {
    // I suppose that 0-indexed element stores id
    if ($item[0] == $product_id) {
        // I suppose that 1-indexed element stores quantity
        $_SESSION['cartitems'][$key][1] += $quantity;
        $found = true;

        // break as certain element found
        break;
    }
}
if (!$found) {
    $_SESSION['cartitems'][] = array($product_id, $quantity);
}
Sign up to request clarification or add additional context in comments.

2 Comments

In case of difficulties I added code for your current $_SESSION. So you can compare which one is simpler)
The second options works better as its easier to implement with the current structure and I don't necessarily know all the items in the session so it would take a bit more writing to make the first option work, but the second option works nicely. Just need to add my check now for if it goes over the stock limit.
0

Heres what I did including final fact check thanks to @u_mulder:

// Set that we dont't see it by default
$found = false;
foreach($_SESSION['cartitems'] as $key => $item) {
    if($item[0] == $itemid) {
        // If it has unlimited stock, who cares, otherwise fact check it
        if($unlimstock == "1") {
            $_SESSION['cartitems'][$key][1] += $quantity;
            $found = true;
            break;
        } else {
            // If it's less than or equal to stock, we can try and add it
            if(($_SESSION['cartitems'][$key][1] + $quantity) <= $stock) {
                // If it has a buy limit, we set max to buy limit and check it
                if($buylimit > 0) {
                    if(($_SESSION['cartitems'][$key][1] + $quantity) <= $buylimit) {
                        $_SESSION['cartitems'][$key][1] += $quantity;
                    }
                } else {
                    $_SESSION['cartitems'][$key][1] += $quantity;
                }
            }
            // Woot, we found it, so we can update it
            $found = true;
            break;
        }
    }
}
// If it wasn't found, we can add it as a new item. This has been fact checked already
if(!$found) {
    $_SESSION['cartitems'][] = array($itemid, $quantity);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.