I have a foreach
loop to check all array of ID
and if
using in_array
to see if any of the arrays of IDs
is equaled my $_POST['id']
as shown below:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
foreach ($_SESSION['cart'] as $item) {
$id = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
For some reason, it keeps adding even when the ID
exist inside the list of arrays of IDs
.
CodePudding user response:
You are just changing the value of $id inside foreach loop. Try to store value in array. Refer the below code:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
$id = array();
foreach ($_SESSION['cart'] as $item) {
$id[] = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}