Jump to content

Eliminating duplicate array values with array_unique in shopping cart


terungwa

Recommended Posts

I am learning to build a shopping cart script. When a new item is added to the cart that already has the new item added, rather than use array_splice to update the existing cart quanties, I want to do the following:

  1. Check if the item already exists in the cart,
  2. provide feedback to the user that, he has already added that item to cart.
  3. Use array_unique to eliminate the duplicate item.

So far, my use of array_unique in my cart.php script below is not working, with regard to providing user feedback.

Note: I have executed array_splice() to be sure the item quantity is increased before attempting to use array_unique to remove the duplicate item.

 

 

I will appreciate any help in resolving this.

 

CART.PHP

if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
	$wasFound = false;
	$i = 0;
	// If the cart session variable is not set or cart array is empty
	if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
	    // RUN IF THE CART IS EMPTY OR NOT SET
		$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
	} else {
		// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
		foreach ($_SESSION["cart_array"] as $each_item) { 
		      $i++;
		      while (list($key, $value) = each($each_item)) {
				  if ($key == "item_id" && $value == $pid) {
					  // That item is in cart already so let's prevent its addition using array_unique()
					  array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
                                          $wasFound = true;
                                          echo 'item already in cart';
					  array_unique($_SESSION["cart_array"]);
				  } // close if condition
		      } // close while loop
	       } // close foreach loop
		   if ($wasFound == false) {
			   array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
		   }
	}
	header("location: cart.php"); 
    exit();
}
Link to comment
Share on other sites

Is there a reason you're not just using conventional array searching to find if the value exists? And then incrementing the count that way?

 

Also, it would probably be easier to store the products in a single array like this:

array(
  //item_id => quantity
  1 => 4
)

That way you can do this to check if the item is already added:

$sessionCart = $_SESSION['cart_array'];
if (isset($sessionCart[$item_id])) {
  $sessionCart[$item_id]++; //I'm pretty sure this works..
  echo "Item already added";
}
$_SESSION['cart_array'] = $sessionCart;
Link to comment
Share on other sites

According to the manual, array_unique returns a new array. So you will to assign the results of array_unique to a new or the same array. And array_unique is not meant to work on multi-dimensional arrays. So, because $_SESSION["cart_array"] is an array of arrays, I think array_unique is not the most appropriate choice to accomplish this step of your process.

Link to comment
Share on other sites

@bsmither and @denno020, thank you for your responses. I made a simple change to my script as shown below, and the output is what i needed.

		// RUN THIS BLOCK OF CODE ONLY IF THE CART HAS AT LEAST ONE ITEM IN IT
		foreach ($_SESSION["cart_array"] as $each_item) { 
		      $i++;
		      while (list($key, $value) = each($each_item)) {
				  if ($key == "item_id" && $value == $pid) {
					  $error='You have already chosen this subscription plan';
					  include 'error.php';
					  die;
					  
				  } // close if condition
		      } // close while loop
	       } // close foreach loop
		   if ($wasFound == false) {
		     $error='You can not choose more than one subscription plan at a time';
                     include 'error.php';
                     die;
		   }
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.