I Would like to remove a variable from a PHP session array when the user chooses 'Remove'.
But when I unset, ALL the variables in the array are deleted.
How I can delete just one variable?
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
$_SESSION['products'][$productName] = $productName;
}
?>
<?php foreach ($_SESSION['products'] as $product): ?>
<div class="echo-product"><?php echo htmlspecialchars($product); ?>
<button type="submit" class="delete-product" value="Remove" >[x]</button>
</div>
<?php endforeach;?>
My code is a bit different from the other posts I found on this site. But I really need help with this code...
Update
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('http://examp.nl/reload.php?addparam', {productName: productName}, function(data) {
$('.echo').html(data);
})
});
$('.delete-product').click(function() {
var productName = $(this).data('product');
$.post('http://examp.nl/reload.php?delparam', {productName: productName}, function(data) {
$('.echo').html(data);
})
});
Update
If I use the following dump
var_dump((unset) $productName);
var_dump($productName);
I get this output. Maybe it is of help...
NULL string(6) "Item Z"