Session variable problem driving me nuts!

Hi

I have some shopping cart code to add items to a shopping cart:

$action = $_GET['action'];
switch ($action) {
	case 'add' :
		if(!$cart) {
			$cart = $_GET['id'];
		} else {
			$cart .= ',' . $_GET['id'];
		}
		break;
	case 'delete' :

This results (for my test run) in a session variable containing the following:

cart|s:5:"1,2,1";

For this example I selected one item twice. In my shopping cart I only show two items because this is expensive artwork, and multiple copies are not available. This is working OK. However, my message which shows how many items are in the cart says 3, I guess because I am just getting a count of the string from the session variable.

So I tried this new code to get rid of duplicate variables:

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

I have tried so many different ways to come up with the correct method. Usually the result is that the cart is emptied.

Any help or hints would be very welcome. If someone can point me to where my logic is going wrong, I would like to try and fix it myself.

Thanks in advance

Cliff

  • Create an array from $cart by splitting on commas
  • Remove duplicates from the array with array_unique
  • Use implode to convert the array into a string of values separated by commas

The code:

$cart = implode(",", array_unique(explode(",", $cart)));

Jeez Dan - you are the Man!

I have been walking around this problem for hours. I “knew” that I had to use array_unique; but I could never, in two lifetimes have come up with such a terrific solution. Most of my tries were at least 10 or so lines long.

My grateful thanks

Cliff

In case stuffing it all in one line makes it hard to read, this is exactly that line is doing:

$array = explode(",", $cart);  //string to array
$array = array_unique($array); //remove duplicates
$cart = implode(",", $array);  //array to string

Thanks for that Dan. A question comes to mind: does stuffing it all in one line make it quicker for the computer to compute the three calls, or does it still see it as three separate operations?

If the answer is that it does make for shorter computing time, is it worth perusing my code to see where this sort of thing can be done?

Thanks again for your help.

Cliff

There’s no appreciable difference.