Adariel Lzinski Adariel Lzinski - 16 days ago 5
PHP Question

foreach only checks first value in array, then creates new value

I'm working on a php shopping cart and I'm trying to have the cart update the quantity of the item, rather than creating new entries for the same item. However when entering a product that is already in the cart, my foreach statement only checks it against the first array value and then creates a new entry for that product.

Can someone please help me work through this and figure out why it's not checking against the whole array list?

Here's my update method:

function CheckForExistingEntry($id, $setOf, $quantity) {
// if the product ID and the SET OF is equal in multiple products, update the quanity instead of making new records
foreach ($_SESSION['shopping_cart'] as $key => $product) {
if ($id == $product['product_id'] && $setOf == $product['setOf']) {
// Update Cart Value
$_SESSION['shopping_cart'][$key]['quantity'] += $quantity;
$_SESSION['shopping_cart'][$key]['price'] *= $_SESSION['shopping_cart'][$key]['quantity'];
break;
} else {
// Add New Cart Value
AddToCart($id, $setOf, $quantity);
break;
}
}
}

Answer

You have a break; in both if and else, which means that it will always break after the first iteration.

Let's remove the else-block, since we just want to continue to the next item if it wasn't found.

Try this: (I've commented the changes):

// Define a variable that holds the state.
$updated = false;

foreach ($_SESSION['shopping_cart'] as $key => $product) {
    if ($id == $product['product_id'] && $setOf == $product['setOf']) {
        // Update Cart Value
        $_SESSION['shopping_cart'][$key]['quantity'] += $quantity;
        $_SESSION['shopping_cart'][$key]['price'] *= $_SESSION['shopping_cart'][$key]['quantity'];

        // Set updated as true and break the loop
        $updated = true;
        break;
    }
}

if (!$updated) {
    // We didn't update any items, add a new item instead
    AddToCart($id, $setOf, $quantity);    
}
Comments