chenci
chenci

Reputation: 113

shopping cart: delete doesn't work as supposed to

I'm having some problem with the "delete" of my shopping cart script (is a case of a switch)

case 'delete':
        if ($cart) {
            $items = explode(',',$cart);
            $newcart = '';
            foreach ($items as $item) {
                if ($_GET['id'] != $item) {
                    if ($newcart != '') {
                        $newcart .= ','.$item;
                    } else {
                        $newcart = $item;
                    }
                }
            }
            $cart = $newcart;
            $_SESSION['cart'] = $cart;
        }
        break;

Example: $_SESSION['cart'] = 1,2,1; The problem is that when a client bought twice the same item, it deletes both. How can i fix it?

Upvotes: 0

Views: 74

Answers (2)

Guilherme Viebig
Guilherme Viebig

Reputation: 6930

You need to set a flag, something like:

$items = explode(',',$cart);
        $newcart = '';
        $flag = false;
        foreach ($items as $item) {
            if ($_GET['id'] == $item && $flag === false) { $flag = true; continue; }


                if ($newcart != '') {
                    $newcart .= ','.$item;
                } else {
                    $newcart = $item;
                }

        }
$cart = $newcart;

Upvotes: 1

Kuba
Kuba

Reputation: 712

This snipped could help:

$items = explode(',',$cart);
$newcart = array();
$deleted = false;
foreach ($items as $item) {
  if (!$deleted && $_GET['id'] == $item) {
    $deleted = true;
    continue;
  }
  $newcart[] = $item;
}
print_r(implode(',',$newcart));

Upvotes: 1

Related Questions