Home > database >  array_push() not working with session in PHP
array_push() not working with session in PHP

Time:05-26

i am working with PHP, I want to store more than two products in SESSION using array_push(). But problem is that after array_push only 2 products is showing in the cart. When i add more than two product then it is not added into the cart.

Here is my Code:

$dataArray = array();

$cartArray = array(
   $code=>array(
       'id' => $id,
       'name' =>$name,
       'price' =>$price,
       'quantity' =>1)
  );
      
if(empty($_SESSION["shopping_cart"])) {
    $_SESSION["shopping_cart"] = $cartArray;
}
else {
    array_push($dataArray, $_SESSION["shopping_cart"], $cartArray);
    $_SESSION['shopping_cart'] = $dataArray;
}   

CodePudding user response:

You can directly assign values to an array like the below mention.

$_SESSION['shopping_cart'][] = $dataArray;

It will create a 2-d array for "shopping_cart" and every time you add $dataArray

it will store in new key so you can get the "shopping_cart" array having all items

For more about array go throgh this :- php arrays

CodePudding user response:

Please find solution below:

<php 
$cartArray = [
[
   'id' => $id,
   'name' =>$name,
   'price' =>$price,
   'quantity' =>1
],
[
    'id' => $id,
    'name' =>$name,
    'price' =>$price,
    'quantity' =>1
 ]
];
if(isset($_SESSION["shopping_cart"])){
if(empty($_SESSION["shopping_cart"])) {
    $_SESSION["shopping_cart"] = $cartArray;
}
else {
    array_push($_SESSION["shopping_cart"], $cartArray);
}  
}
?>
  • Related