Jump to content

Recommended Posts

I have a simple shopping cart that I put together which allows me to add and remove items. I'm using an array to store the values. The items are either in the cart, or not in the cart - meaning there is quantity to select. I'm trying to figure out how to compare a product ID to the current array string to see if it already exists.

 

Meaning, if they are on the product page for Apples, they can't add the product again. Ultimately I would like the "add to cart" button to change to a "remove from cart" if it is already in there.

 

Having said that, if the above thought is getting to messy, is it possible to check to see if the product ID for Apples is already in the array, and if so it doesn't add it in again?

 

Here is the code that adds to the cart:

session_start();

$cart 	= $_SESSION['cart'];
$action	= $_GET['action'];

switch ($action) {

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

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;
	}
	break;

case 'update':
if ($cart) {
	$newcart = '';
	foreach ($_POST as $key=>$value) {
		if (stristr($key,'qty')) {
			$id = str_replace('qty','',$key);
			$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
			$newcart = '';
			foreach ($items as $item) {
				if ($id != $item) {
					if ($newcart != '') {
						$newcart .= ','.$item;
					} else {
						$newcart = $item;
					}
				}
			}
			for ($i=1;$i<=$value;$i++) {
				if ($newcart != '') {
					$newcart .= ','.$id;
				} else {
					$newcart = $id;
				}
			}
		}
	}
}

$cart = $newcart;
break;
}

$_SESSION['cart'] = $cart;

 

And here is the code that displays the quantity. This will list, for example, 6 items in your cart even if you only have 2 of the same.

 

function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
	return '<p class="shopping-cart"><a href="'.$siteURL.'/index">Your Cart Is Empty</a></p>';
} else {
	// Parse the cart session variable
	$items = explode(',',$cart);
	$s = (count($items) > 1) ? 's':'';
	return '<p class="shopping-cart"><a href="'.$siteURL.'/cart">You Have '.count($items).' Item'.$s.' In Your Cart</a></p>';
}
}

 

Thanks in advance for any help you could give!

Link to comment
https://forums.phpfreaks.com/topic/240253-finding-a-value-in-an-array/
Share on other sites

Instead of storing the items in your cart as a comma-delimited string, why not use an array? For example:

 

function addToCart($id) {
    if (!in_array($id, $_SESSION['cart'])) {
        $_SESSION['cart'][] = $id;
    }
}

switch ($action) {
    case 'add':
        addToCart($_GET['id']);
        break;

Alright, I have cleaned up my code and taken the advice of boompa. I am down to just two issues now!

 

1. How to keep the quantity to becoming more than one per item quantity wise.

2. On the product page, checking the array to see if a product is already in the cart (to remove the "add to cart" button)

 

// SHOPPING CART ADD, REMOVE AND EMPTY

$product_id = $_GET[id];	 //the product id from the URL 
$action 	= $_GET[action]; //the action from the URL 

switch($action) {	//decide what to do	

	case "add":
		$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id 
	break;

	case "remove":
		$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
		if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function)		
	break;

	case "empty":
		unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
	break;

}

 

This code I'm using to count the  number of items currently in the cart:

 

function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
	return '<p class="shopping-cart"><a href="'.$siteURL.'/index">Your Cart Is Empty</a></p>';
} else {
	// Parse the cart session variable
	$items = $cart;
	$s = (count($items) > 1) ? 's':'';
	return '<p class="shopping-cart"><a href="'.$siteURL.'/cart">You Have '.count($items).' Item'.$s.' Scheduled</a></p>';
}
}

 

To check against the shopping cart to see if a product has already been added, am I on the right track?

if($_SESSION['cart']) {

	if (($_SESSION['cart'][$product_id]) == $id) { echo "This Item Is Already In Your Cart"; }

}

Use this code

print_r($_SESSION['cart']);

 

I get the following:

Array ( [56954] => 1 [56950] => 1 [57541] => 1 [57052] => 1 [56992] => 1 )

 

So I was thinking something like this would work (but it doesn't)

if ($_SESSION['cart'] == $id) { echo "IN CART!"; } else { echo "NOT IN CART!"; }

I think I have that one part working (although I'm sure there is a better way).

foreach($_SESSION['cart'] as $product_id => $quantity) {
if ($product_id == $synonum) { $inCart = "Yes"; }
}

 

Now, any idea how I can limit the quantity to just one per item?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  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...

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.