Reputation: 13
I have session stores arrays of items' informations, each items has a quantity i want when the user select the same items just increase the quantity instead of add it again. when i increase quantity for one items it's ok, but when i increase the quantity for many items only it's ok for the first one, other are increasing but at the same time they duplicated with quantity 1
Example i choose x 3 times and y 2
x3 2 y 1y 1y
//if it's the first item
if ( !isset ($_SESSION['Cart']))
{
$CartItem = array ($I_ID,$I_Name,$I_Price,$I_img,$quantity);
$_SESSION['Cart'][] = $CartItem;
header('Location:salad.php');
}
//if the session contains items check if the item already exist
else if (isset ($_SESSION['Cart']))
{
foreach( $_SESSION['Cart'] as $y )
{
if( $y[1] == $I_Name )
{
$_SESSION['Cart'][$i][4]++; //increment quantity
header('Location:salad.php');
break;
}
else{
$CartItem = array($I_ID,$I_Name,$I_Price,$I_img,$quantity);
$_SESSION['Cart'][] = $CartItem;
header('Location:salad.php');
}
$i++;
}
}
?>
Upvotes: 1
Views: 133
Reputation: 1567
The reponse is here :
{
foreach( $_SESSION['Cart'] as $y )
{
if( $y[1] == $I_Name )
{
$_SESSION['Cart'][$i][4]++; //increment quantity
header('Location:salad.php');
break;
}
else{
$CartItem = array($I_ID,$I_Name,$I_Price,$I_img,$quantity);
$_SESSION['Cart'][] = $CartItem;
header('Location:salad.php');
}
$i++;
}
}
If the first item is not the same os $i_NAME you add an item that s why you have a lot of items.
I would do something like :
{
$addItem = true;
foreach( $_SESSION['Cart'] as $y )
{
if( $y[1] == $I_Name )
{
$_SESSION['Cart'][$i][4]++; //increment quantity
$addItem = false;
header('Location:salad.php');
break;
}
$i++;
}
if($addItem){
$CartItem = array($I_ID,$I_Name,$I_Price,$I_img,$quantity);
$_SESSION['Cart'][] = $CartItem;
header('Location:salad.php');
}
}
}
And you render it better with reference on &$y and don t use $i++;
Upvotes: 1