I have a simply cart array, that I want to update if the user selects the same product again. If they already have 5 pencils in their cart, and they add to cart 4 more pencils, I want them to have 9 pencils in their cart, not two entries for pencils of 5 and 4.
The code I have this:
$sub = array("id" => $_POST['pID'], "name" => $_POST['pName'], "price" => $_POST['pPrice'], "quantity" => (int) $_POST['pQuant']);
$updated = false;
foreach($cart as $c)
{
if($c['id']==$_POST['pID']) {
var_dump($c);
echo "<br>";
$c['quantity'] += (int) $_POST['pQuant'];
var_dump($c);
echo "<br>";
var_dump($cart);
echo "<br>";
$updated = true;
}
}
if(!$updated) {$cart[] = $sub;}
For some stupid reason, (Im sure it's a really obvious thing i'm missing here), the first var_dump
of $c is fine. That's the original values. Then the second var_dump
, has the number added onto it. However on the third var_dump
, of $cart
, The value hasn't changed?
I don't get why.
Within the foreach
the variable $c
is only a copy of the basket item, so you update the copy, but not the original item within $cart
. This can be circumvented by using a reference for $c
instead:
foreach($cart as &$c)
Notice the &
in front of $c
.
foreach
creates a copy of the original array. To work with the original array, use this:
foreach(array_keys($cart) as $k) {
$c = &$cart[$k];
// rest of code
}
The problem is, that foreach uses not references. It uses values. If you want to change $cart
you have two ways:
foreach($cart as $key => $c) {
$cart[$key]['quantity'] = += (int) $_POST['pQuant'];
}
The alternative:
foreach($cart as &$c) {// use a reference
[...]
}