hossam hossam - 4 months ago 6
PHP Question

Php session doesn't store on the same array but creates new one

I am trying to store variables on a session array on a multiple page web site but it keeps on replacing the data and not storing it whenever a new data is added, I would be very thankful if anyone can help I have been trying to work on it for a long time and I read different helpful tips about it but I still don't know what I am doing wrong in here.

the code is:

if (empty($_SESSION['cart'])){
$_SESSION['cart'] = array();}

if(isset($_SESSION['count'])){
$count_cart= $_SESSION['count'] ;
}


if (isset($_GET['id'])) {
if(isset($_SESSION['cart'])){ $_SESSION['cart']= array();}


array_push($_SESSION['cart'], $_GET['id'] );






foreach ($_SESSION['cart'] as $key => $count_cart) {var_dump( $_SESSION['cart']);
}


}

Answer

Check your code :

if (isset($_GET['id'])) {
    if(isset($_SESSION['cart'])){

        // this line RESETS your `$_SESSION['cart']` data 
        // and creates empty array
        // so you need to remove this line
        $_SESSION['cart']= array();

        array_push($_SESSION['cart'], $_GET['id'] );
    }
}
Comments