Jeremy P Jeremy P - 10 months ago 41
PHP Question

Adding an element to a multidimensional array which is already defined in PHP?

I'm building a simple shopping cart without a database, just using an array.

I can add the item to the shopping cart which it has the name and price. I want to be able to add more elements such as quantity at the point when I update the shopping cart.

This is my working code that displays name and price.

$_SESSION['cart'] = array($products[$itemid]);

$itemid only contains the name and price.

I've tried several ways to add an element, which have failed. How can I add an element at this point?

$_SESSION['cart'] = array($products[$itemid ,'qty' => 1]);
$_SESSION['cart'] = array($products[$itemid] ,'qty' => 1);
array_push($_SESSION['cart'], $products[[$itemid, 'qty' => 1]]);


If the $products[$itemid] is an array with name and price as keys Try This to add qty to it :

$_SESSION['cart'] = array(array_merge($products[$itemid], ['qty' => 1]);