Jump to content
Killersites Forums

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


Recommended Posts

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);

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"];


Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...