Home > OS >  Display a nested session variable in PHP
Display a nested session variable in PHP

Time:09-16

I'm trying to echo product_name with

echo $_SESSION["shopping_cart"]["product_name"];

but that's not working.

This is var_dump($_SESSION)

array(4) {
  ["shopping_cart"]=>
  array(1) {
    [0]=>
    array(4) {
      ["product_id"]=>
      string(2) "99"
      ["product_name"]=>
      string(32) "Booster Juice Concentrate"
    }
  }

How can I echo "product_name"?

TIA

CodePudding user response:

Your session have shopping_cart and shopping_cart is a array, so the right one is

echo $_SESSION["shopping_cart"][0]["product_name"];

because you wanna get the name of first product, right?

CodePudding user response:

Your array of shopping cart is an array that contains an array of different items in it. Then each item in that array is an array itself. To echo out the first product name you would write:

echo $_SESSION["shopping_cart"][0]["product_name"];

Eventually, you will need to go over each of these elements in a for loop when you have more than one product in the cart

foreach($_SESSION["shopping_cart"] as $product){
  echo $product['product_name'] . "<br>";
}
  • Related