Using PHP, my objective is to prevent the addition of a duplicate ID into a SESSION cart. The ID is passed from a form. The error message works for the first item only. Other items already in the cart bypass the conditional statement and are added to the array, although the first item at any point gets caught by it. Various trial and error remedies have failed.
Any assistance is appreciated. Let me know if this challenge is not described clearly. Thank you in advance.
Here's the code:
// If user clicks add button
if(isset($_POST['action']) && $_POST['action'] === 'Add'){
// If cart has content, check if new content already in cart
if(!empty($_SESSION['cart'])){
foreach($_SESSION['cart'] as $id){
if($_POST['id'] === $id){
$errMsg = 'Item ' . $_POST['id'] . ' already in cart.';
include 'error.html.php';
exit();
}else{
// Add new content to cart
$_SESSION['cart'][] = $_POST['id'];
header('Location: .');
exit();
}
}
}