my goal is when user adds a product thats already in the cart, it will retain the product name and it will add 1 to the current quantity

my code is:

$item_found = false;

$index_of_array = 0;

if(isset($_POST['product_id']))
{
	$product_id = $_POST['product_id'];

	if(!isset($_SESSION['cart_array'] ) || empty($_SESSION['cart_array'] ))
	{
		$_SESSION['cart_array'] = array(1 => array("product_id" => $product_id, "quantity" => 1));
	}
	else
	{
		foreach($_SESSION['cart_array'] as $each_item)
		{
			$index_of_array++;
			
			while(list($key, $value) = each($each_item))
			{
				if($key == "product_id" && $value == $product_id)
				{
					array_splice($_SESSION['cart_array'], $index_of_array-1, 1, array(array("product_id" => $product_id, "quantity" => $each_item['quantity']+1)));
					$item_found = TRUE;
				}
			}
			if($item_found == FALSE)
			{
				array_push($_SESSION['cart_array'], array("product_id" => $product_id, "quantity" => 1));
			}
		}
	}
}

lets see if code will be more clear:

$item_found = false;
 
$index_of_array = 0;
 
if(isset($_POST['product_id']))
{
	$product_id = $_POST['product_id'];
 
	if(!isset($_SESSION['cart_array'] ) || empty($_SESSION['cart_array'] ))
	{
		$_SESSION['cart_array'] = array(1 => array("product_id" => $product_id, "quantity" => 1));
	}
	else
	{
		foreach($_SESSION['cart_array'] as $each_item)
		{
			$index_of_array++;
 
			while(list($key, $value) = each($each_item))
			{
				if($key == "product_id" && $value == $product_id)
				{
					array_splice($_SESSION['cart_array'], $index_of_array-1, 1, array(array("product_id" => $product_id, "quantity" => $each_item['quantity']+1)));
					$item_found = TRUE;
				}
			}
			if($item_found == FALSE)
			{
				array_push($_SESSION['cart_array'], array("product_id" => $product_id, "quantity" => 1));
			}
		}
	}
}
Member Avatar for diafol

so what's problem?

i figured it out. thanks! anyway I could delete this post?

Member Avatar for diafol

You could ask, but I doubt whether the mods/admins will do it. How about you post your solution and mark the thread solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.