user5313398 user5313398 - 2 months ago 15
PHP Question

Session value not printing other key and their value

I can set this session values.

<?php
$_SESSION['cart_items'][$name]['price']=$price;
if (!empty($quantity)) {
$_SESSION['cart_items'][$name]['quantity']=$quantity;
}
?>


But when I run this

<?php
foreach($_SESSION['cart_items'] as $key => $value) {
echo $key ;
echo $value;
//echo "<br>prod product_price : ".$product_price;
}
?>


It only print the $_SESSION['cart_items'][$name]['price']. It doesn't not print the quantity value. How can I print like for the $name the price, quantity etc.

Here is my full codes

if(!isset($_SESSION['cart_items'])){
$_SESSION['cart_items'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}

// else, add the item to the array
else{
$_SESSION['cart_items'][$name]['price']=$price;

if (!empty($quantity)){
echo "adding qty";
$_SESSION['cart_items'][$name]['quantity']=$quantity;
}

// redirect to product list and tell the user it was added to cart
// header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}

Answer

When you create your new item, you need to create an Array at [$name] since an Item is an array for you. Without doing so, you were trying to assign a value as if it was an array but it was just a simple value.

<?php 

    if(!isset($_SESSION['cart_items'])){
        $_SESSION['cart_items'] = array();
    }

    // check if the item is in the array, if it is, do not add
    if(array_key_exists($id, $_SESSION['cart_items'])){
        // redirect to product list and tell the user it was added to cart
        header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
    }

    // else, add the item to the array
    else{
        //Since your item is an array, you need to create it.
        $_SESSION['cart_items'][$name] = array();
        $_SESSION['cart_items'][$name]['price']=$price;

        if (!empty($quantity)){
              echo "adding qty";
            $_SESSION['cart_items'][$name]['quantity']=$quantity;
        }

        // redirect to product list and tell the user it was added to cart
       // header('Location: products.php?action=added&id' . $id . '&name=' . $name);
    }