0

I am working on a function that adds an item to a cart. If the item already exists in the cart, increase its quantity amount by 1. If it doesn't, I want to add the item array in the next position in the cart array. Here's my code that I am using where $add_to_cart is the item ID:

if ($add_to_cart) {
    $added = false;
    foreach ($cart as &$item){
        if ($item['id'] == $add_to_cart){
            $item['qty'] += 1;
            $added = true;
        }
    }
    if (!$added) {
        $cart[count($cart)]['id'] = $add_to_cart;
        $cart[count($cart)]['qty'] = 1;
    }
    $_SESSION[$session_id]['cart'] = $cart;
}

When I use this code, it appends the ID of the item as the second last element, then the qty value as the last element. How can I make this work?

0

3 Answers 3

2

Your problem is when you are adding new elements to the cart:

if (!$added){
    $cart[count($cart)]['id'] = $add_to_cart;
    $cart[count($cart)]['qty'] = 1;
}

You are calling count($cart) in each line. After the 1st line is called, the count is different, so the 2nd line adds a different element. What you want is to push an array onto the array. Try this:

if (!$added){
    $cart[] = array(
        'id' => $add_to_cart,
        'qty' => 1
    );
}
Sign up to request clarification or add additional context in comments.

Comments

2

Restructure your shopping cart array to something like this:

array(
    'id' => 'qty',
    .
    .
    .
);

What I mean by that is that you don't have to loop through the array the way you do.

You can just check to see if the index at key is set, then increment the value at that index.

if (isset($item[$add_to_cart])) { // formerly if(array_key_exists($add_to_cart, $item)) {
    $item[$add_to_cart]++;
} else {
    $item[$add_to_cart] = 1;
}

By doing this your performance will go from O(n) to O(1) and you go from 11 lines of code to 5.

8 Comments

Is there a reason you're using array_key_exists rather than isset($item[$add_to_cart]) ?
Making the product ids the array's keys is much faster :-)
@HighwayofLife not really. Is there better performance from isset()?
@HighwayofLife isset() is faster, but not significantly. According to this benchmark test "The above benchmark executed on PHP 5.4 shows that while isset() is 2.5 times faster taking a mere 0.0219 seconds vs 0.0549 seconds taken by array_key_exists(), both operations are extremely quick and take a fraction of a second even when doing 100k operations. Any "optimization" between the calls is purely within the super-micro-micro optimization realm and is not going to make any application measurably faster."
@HighwayofLife in this case, I must concede that isset() is more appropriate.
|
0

As @Matt said, you might restructure your shopping cart array. But if you really want to use your current cart structure :

$cart = array();

function add_item($cart, $item_id)
{
    if(is_array($cart))
    {
        $added = false;

        for($i=0; $i<count($cart); $i++)
        {
            if($cart[$i]['id'] == $item_id)
            {
                $cart[$i]['qty'] ++;
                $added = true;
                break;
            }
        }

        if($added == false)
        {
            $i = count($cart);

            $cart[$i]['id'] = $item_id;
            $cart[$i]['qty'] = 1;
        }
    }

    return $cart;
}

$cart = add_item($cart, 50);
$cart = add_item($cart, 50);
$cart = add_item($cart, 50);

$cart = add_item($cart, 25);
$cart = add_item($cart, 25);

$cart = add_item($cart, 10);

var_dump($cart);

It prints :

array
  0 => 
    array
      'id' => int 50
      'qty' => int 3
  1 => 
    array
      'id' => int 25
      'qty' => int 2
  2 => 
    array
      'id' => int 10
      'qty' => int 1

EDIT : WITH A BETTER STRUCTURE

$cart = array();

function add_item($cart, $item_id)
{
    if(is_array($cart))
    {
        if(array_key_exists($item_id, $cart))
        {
            $cart[$item_id]++;
        }
        else
        {
            $cart[$item_id] = 1;
        }
    }

    return $cart;
}

$cart = add_item($cart, 50);
$cart = add_item($cart, 50);
$cart = add_item($cart, 50);

$cart = add_item($cart, 25);
$cart = add_item($cart, 25);

$cart = add_item($cart, 10);

var_dump($cart);

It prints :

array
  50 => int 3
  25 => int 2
  10 => int 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.