简体   繁体   中英

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.

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']);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM