Timonvw Timonvw - 7 months ago 14
PHP Question

PHP Session Array not working when adding more than 2 items

I want to add products to my array, everytime when I add a product it replaces the old one in the array.

when I add 2 things than its okay: Array ( [0] => 2 [1] => 8 )
But when I try to add a third item or more it replaces the second item in the array: Array ( [0] => 2 [1] => 10 )

Can someone help me please, here is my code:

session_start();

if(isset($_POST['inCart']))
{
$id = $_POST['id'];

if(!empty($_SESSION['cart']))
{
$session = $_SESSION['cart'];
$session[] = $id;

print_r($session);
}

else
{
$_SESSION['cart'] = array($id);
}
}

Answer

As i see you forgot set SESSION with new data

if(!empty($_SESSION['cart']))
       {     
          $session = $_SESSION['cart'];
          $session[] = $id;

          $_SESSION['cart'] = $session;

          print_r($session);
       }