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?
You should treat the session variable as an array instead of string. Append to it using the
[]operator:You can also use
array_push()if you want. Later you can iterate over the products like: