Veltar
Veltar

Reputation: 741

How do I store the same values in a session?

I'm building a checkout system, and I'm trying to add products to a session variable. But I'm stuck on how I should save them. How can I save for example 5 products?

I try to use something like this, but that doesn't work:

$_SESSION['cart']['productIds']['id'] .= $_POST['productid'];
$_SESSION['cart']['productPrices']['price'] .= $_POST['price']; 

The output is something like this (twice a product with id 2 and price 20):

Array ( [productIds] => Array ( [id] => 22 ) [productPrices] => Array( [price] => 2020 )

I would like it to be saved as an array, what's the best approach for this?

Upvotes: 1

Views: 64

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173562

You should treat the session variable as an array instead of string. Append to it using the [] operator:

$_SESSION['cart']['products'][] = array(
    'id' => $_POST['productid'],
    'price' => $_POST['price'],
);

You can also use array_push() if you want. Later you can iterate over the products like:

foreach ($_SESSION['cart']['products'] as $product) {
    echo $product['id'], ': ', $product['price'], "\n";
}

Upvotes: 3

Related Questions