0

I have an array being set into $_SESSION["cart_array"] and the output is as such when items are in the cart.

Array ( [0] => Array ( [item_id] => 1 [quantity] => 6 ) [1] => Array ( [item_id] => 2 [quantity] => 1 ) )

I am trying to create a foreach loop to go through and count up the "quantity" values as to get a total cart item count, so far i have the below but i just cannot figure out how to get it into a string variable so i can display it on other pages.

    $cartCount = array();
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartCount = 0;
} else {
    foreach ($_SESSION["cart_array"] as $each_item) {
        //$cartCount += $each_item['quantity']; <-- commented out as not working.
        //$cartCount[$each_item['item_id']] += $each_item['quantity']; <-- commented out as not working.
    }
    //Print array for debugging purposes
    print_r($_SESSION["cart_array"]);
}  

1 Answer 1

1

This has to work:

<?php

session_start();

$cartCount = 0;
if(isset($_SESSION['cart_array']) AND is_array(@$_SESSION['cart_array'])){
    foreach($_SESSION['cart_array'] AS $each_item){
        $cartCount = $cartCount + $each_item['quantity'];
    }
}

echo $cartCount;

?>
Sign up to request clarification or add additional context in comments.

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.