Session array unset and delete row

1k views Asked by At

I get the id of a product and try to delete from my session array.I use unset and everything goes well but when i try to display the data in a loop the session still have the deleted row so i get the error Undefined offset: 0. I use a second session that just has the count of the first so when i delete one row it works fine.However when i try the same to the multidimensional session ($_SESSION['cart'] = $_SESSION['cart'] -1;) it doesnt work and i get the error Unsupported operand types..

So to sum up i need to delete a specific data from the session array and when i use unset it does delete it but the array still has all the indexes if i have 3 products i delete the second one and when i display them the array still have index 0,1,2..

Here is my code

$cart = $_SESSION['cart'];
$c=$_SESSION['c'];

$id=$_GET['id'];


unset($_SESSION['c'][$id]);
unset($_SESSION['cart'][$id]);


$_SESSION['c'] = $_SESSION['c'] -1;
$_SESSION['cart'] = $_SESSION['cart'] -1;
1

There are 1 answers

1
joy d On BEST ANSWER

Replace

$_SESSION['c'] = $_SESSION['c'] -1; 

by

$_SESSION['c'] = array_values($_SESSION['c']);

"-1" will throw error since you are trying to subtract numeric value from a N-dimensional array. array_values will return you updated $_SESSION['c'] after unset/delete operation is done.

P.S. Update your code accordingly for $_SESSION['cart'] as well.