foreach($cart_items as $item) {
foreach($item["id"] as $key => $val) {
foreach($item["quantity"] as $i => $value) {
if ($key == $i){
$temp_array = $cart_items;
$array = array_pop($temp_array);
var_dump($temp_array);
if (isset($_REQUEST["element_id_$i"]) && isset($_REQUEST["quantity_$i"]) && isset($value)) {
$j = array_search($_REQUEST["element_id_$i"], $temp_array);
if( $j==$temp_array[$i]) {
echo "<b>SAME PRODUCT ADDED</b>";
$value += $_REQUEST["quantity_$i"];
unset($_REQUEST["element_id_$i"]);
}
}
}
}
}
}
As soon as I do that I can see just in the first four lines that you've got a whole loop going on that's not needed.
foreach($cart_items as $item) {
foreach($item["id"] as $key => $val) {
$value = $item["quantity"][$key];
$temp_array = $cart_items;
$array = array_pop($temp_array);
var_dump($temp_array);
if (isset($_REQUEST["element_id_$i"]) && isset($_REQUEST["quantity_$i"]) && isset($value)) {
$j = array_search($_REQUEST["element_id_$i"], $temp_array);
if( $j==$temp_array[$i]) {
echo "<b>SAME PRODUCT ADDED</b>";
$value += $_REQUEST["quantity_$i"];
unset($_REQUEST["element_id_$i"]);
}
}
}
}
Still not clear how you've got things structured where you have to remove something that you presumably just added nanoseconds earlier (but somehow then lost making array_pop
necessary because fortunately you know it's the last one added), but having the IDs and quantities in separate arrays looks like a hazard, since you have to do a lot of search back and forth between them to pair them up.
I don't know what your $val
is since it's unused here, but if it's not being at all, perhaps store the item quantities there instead of in a separate array. A one-dimensional $cart_items
array that is a list of IDs and quantities, in other words:
$cart_items = [
10001 => 42,
10002 => 17,
10003 => 21,
....
];
If you have to carry more information in the $cart_items
array for each item:
$cart_items = [
10001 => ['quantity' => 42, 'more' => 'information', 'foo' => 'bar'],
10002 => ['quantity' => 17, 'more' => 'information', 'foo' => 'baz'],
10003 => ['quantity' => 21, 'more' => 'information', 'foo' => 'wibble'],
....
];
For convenience that "more" information can include a repeat of the ID so that you can retrieve it from any given $cart_item
element instead of having to search or guess.
$cart_items = [
10001 => ['id' => 10001, 'quantity' => 42, 'more' => 'information', 'foo' => 'bar'],
10002 => ['id' => 10002, 'quantity' => 17, 'more' => 'information', 'foo' => 'baz'],
10003 => ['id' => 10003, 'quantity' => 21, 'more' => 'information', 'foo' => 'wibble'],
....
];