Cart array $_SESSION['cart'] not prininting cart items properly

Viewed 35

I am doing shopping cart functionality on an ecommerce site via $_SESSION. I added cart items successfully on every click in $_SESSION['cart'] array. but unable to print it correctly. I made an associative array which is being a problem to handle correctly. I dont know how to show cart items properly, tried merge array += $item or anything but nothing is working.

Here is my code ..

//add  item to cart 
<?php 

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

 $item = array("pid"=>$_POST['pid'], "name"=> "bloom flowers");

 array_push($_SESSION['cart'],$item);
 echo "Done!";
 ?>

//displaying cart items

<?php include 'navbar.php';
session_start();
if(isset($_SESSION['cart'])){
foreach ($_SESSION['cart'] as $value){
     echo '<h5>'.$value.'</h5>';
     }
 }

// print_r($_SESSION['cart']);
 ?>
1 Answers

For your case, if you want to display the data of say "name" , please use $value['name']

Hence, change the block

foreach ($_SESSION['cart'] as $value){
     echo '<h5>'.$value.'</h5>';
     }

to

foreach ($_SESSION['cart'] as $value){
     echo '<h5>'.$value['name'].'</h5>';
     }

Do the same for pid if you want.

Hence, the whole code (fully working) is :

<?php 

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

 $item = array("pid"=>'1', "name"=> "Mary");

 array_push($_SESSION['cart'],$item);

foreach ($_SESSION['cart'] as $value){
     echo '<h5>'.$value['name'].'</h5>';
     }

 ?>
Related