brown.cn
brown.cn

Reputation: 151

Persistent Variable in a session in PHP

I did:

<?php 
session_start();
//require_once ('connection.php');
$cart1 = array();
$cart2 = array();

$_SESSION['cart1'] = $cart1;
$_SESSION['cart2'] = $cart1;
array_push($_SESSION['cart1'],$sel);
print_r($_SESSION['cart1']);

?>

with $sel having a different value each time a form is selected but instead of appending to the array, it creates a fresh one with the new data. What I want to do is create a persistent array variable that I can keep modifying without it deleting and resetting to the new value. Just started using sessions and I’m out of options. Help please.

Upvotes: 0

Views: 238

Answers (1)

Crisp
Crisp

Reputation: 11447

You're initializing your carts as empty arrays on every request, you need to only initialize if the session arrays don't already exist

<?php 
session_start();
//require_once ('connection.php');
if (!isset($_SESSION['cart1'])) {
    $_SESSION['cart1'] = array();
}
if (!isset($_SESSION['cart2'])) {
    $_SESSION['cart2'] = array();
}

array_push($_SESSION['cart1'],$sel);
print_r($_SESSION['cart1']);

?>

Upvotes: 3

Related Questions