Update shopping cart by adding quantities together if the same product is chosen

This is the code that I’m using for a shopping cart in order to update the quantity if the same product id is chosen.

$cart_items is a two-dimensional session array composed of the id session array and the quantity session array. While looping through $cart_items, I create a temporary array $temp_array so that I can execute some logic on the array without changing the normal output. $temp_array is the $cart_items array without the last items which would be the $_REQUEST id and the $_REQUEST quantity. So the two $_REQUESTs are popped off with array_pop and then the remaining $_SESSIONs are compared to the $_REQUEST id with

$j = array_search($REQUEST["element_id$i"], $temp_array);
$j is now the key that corresponds to the id in $temp_array where the $_REQUEST id has been found.

if( $j==$temp_array[$i])

If $j is the key of the item in $temp_array, then the $_REQUEST is unset and the quantities for the item are added together.

There are two problems with this code. First of all the var_dump of the $temp_array is always an empty array but I am expecting to get an array with just the last element popped off. Secondly,
I get the error “Undefined offset” for the $i variable in this line of the code: if( $j==$temp_array[$i])

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"]);
}}}}}}
Sponsor our Newsletter | Privacy Policy | Terms of Service