Dan Dan - 1 year ago 85
PHP Question

Unsetting an item from an array in a session

I am trying to remove an item from my array in a stored session. I have attempted the following but it reverses and actually adds more!

So here is my foreach where the product shows in the cart with a button to remove from the cart:

foreach ($_SESSION['products'] as $product) {
$name = $product['name'];
$id = $product['id'];
$price = $product['price'];
$img = $product['img'];
$sku = $product['sku'];
$description = $product['description'];

echo '<a href="single_product.php?product_id=' . $product['products'] . '">';
echo "<img src='$img'><br />";
echo "Product: $name<br />";
echo "Price: $price | ID: $id<br />";
echo "$description";
echo '</a><br /><br />';
echo '<form action="removeItem.php" method="post">
<input type="hidden" name="product_id" value="' . $product['id'] . '" />
<button name="removeItem">Remove</button>

$sum += $price;


And here is the form to remove it but it actually adds more when you hit remove:

$_SESSION['products'][] = $itemid;
$id = $_POST['id'];


Answer Source

Try something like this:

$product_id = $_POST["id"];
foreach($_SESSION['products'] as $key=>$product) {
   if($product['id'] == $product_id) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download