1

After a button is being pressed, 3 values are put in into a multidimensional array in PHP. I've checked the values before assigning in the same brackets and it seems to have the correct value. However, when I add the values like this:

if (isset($_POST['add_to_cart'])) {
    $count = count($_SESSION['shopping_cart']);
    echo "Count: $count<br />";

    $_SESSION['shopping_cart'][$count]['product_id'] = $_POST['product_id'];
    $_SESSION['shopping_cart'][$count]['tier'] = $_POST['tier'];
    $_SESSION['shopping_cart'][$count]['division'] = $_POST['division'];
}

The output shows that the array $_SESSION['shopping_cart'] is empty and has no values.

if (empty($_SESSION['shopping_cart'])) {
    echo "Your cart is empty.<br />";
}
else {
    //Display products in cart
    foreach($_SESSION['shopping_cart'] as $id => $product) {
        echo $product['tier'] . $product['division'] . "<br />";
    }
}

I've came to the conclusion that I assign the values in a wrong way. What am I doing wrong? Thanks for the help!

EDIT: forgot to add that the array is already initialized at the beginning!

if(!isset($_SESSION['shopping_cart'])) {
    $_SESSION['shopping_cart'] = array();
}
7
  • Is it possible that $_SESSION['shopping_cart'] is never initialized like so: $_SESSION['shopping_cart'] = array(); Commented Mar 30, 2016 at 23:19
  • @Will thanks for writing, I forgot to add that to the post, It's already initialized. Commented Mar 30, 2016 at 23:22
  • 1
    No prob. And you're also calling session_start();? I think we might need to see more of the code. Commented Mar 30, 2016 at 23:25
  • 1
    Wow that was it @Will Thanks so much for the help. It's my first day programming with PHP so I'm a beginner, going to add the answer to the question. Commented Mar 30, 2016 at 23:27
  • You should not use count($_SESSION['shopping_cart']) as an index for its elements. If the cart has three items, $_SESSION['shopping_cart'][$count]['product_id'] will try to get $_SESSION['shopping_cart'][3]['product_id'] which does not exist. Commented Mar 30, 2016 at 23:28

1 Answer 1

3

I forgot to add the session_start(); to the code. That's why the Session array didn't work! Thanks for the help @Will

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

1 Comment

Yes, I was trying but can't until tomorrow since stackoverflow said that I can only accept my own answer after 2 days.

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.