1

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;
7
  • 1
    By the looks of things you're trying to subtract from an array a int. It doesn't make sense. As $_SESSION['c'] is in fact, an array and not an int(or float, or whatever). Commented Jun 9, 2015 at 11:05
  • i know i try actually to decrease the index of the array but dont know how. Commented Jun 9, 2015 at 11:08
  • 1
    Ah, well that's a whole different matter. Just do $_SESSION['c'] = $_SESSION[VALUE YOU WANT GOES HERE]. So basically rewrite the index c of the $_SESSION. Commented Jun 9, 2015 at 11:09
  • well $_SESSION['c'] = $_SESSION['c'] -1; this line works i m having issue with this line $_SESSION['cart'] = $_SESSION['cart'] -1; the session array had 3 products and when i delete one of them the array still have 3 products but the one i unseted is empty so the array has 1 empty cell that i dont wont to be empty i just want to delete it so the 2 products will go 'up' and have the indexes 0 and 1.. does that make sense? sorry .. Commented Jun 9, 2015 at 11:15
  • So you want to change the array keys and sort them basically? Commented Jun 9, 2015 at 11:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

$_SESSION['c'] = array_values($_SESSION['c']); solved the problem of mine, thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.