-1

Is there any possible way to delete element from array? It is shopping cart storing item IDs. I want to make delete function.

For example - cart_handler.php?delete=2687

array(5) { [1967]=> float(1) [1966]=> float(1) [2233]=> float(5) [2687]=> float(1) [2081]=> float(4) } 
rghome
  • 8,529
  • 8
  • 43
  • 62
Zan Kravitz
  • 41
  • 1
  • 5
  • 2
    unset($array[key]) does not work? – Yurich Feb 10 '16 at 14:22
  • show you code how to you delete this element. – Naumov Feb 10 '16 at 14:26
  • if ( isset($_GET['delete']) ) { $item_id = $_GET['delete']; unset($CART[$item_id]); header('Location: /?page=cart'); } – Zan Kravitz Feb 10 '16 at 14:27
  • The reason `unset($array[key])` doesn't work is because the key is not the product ID, that is the value. The keys in the array will be 0, 1, 2, etc. So you have to search for the value's key before unsetting it. I've explained what I mean better in my answer hopefully ^^. – Mikey Feb 10 '16 at 14:33

1 Answers1

1

Yes you can, the easiest way would be to search for the item ID in the array, and then unset the key associated with it -- and then as an extension you could re-base the array to fix the array keys. Please Note: I haven't put any validation on the $arrayKey and what it returns, you should ensure that the array_search function is returning as expected before unsetting the array key just to be safe.

So something like this:

$data = [1967, 1966, 2233, 2687, 2081];
$arrayKey = array_search(1966, $data);
unset($data[$arrayKey]);

The specified product ID would be unset by that, just replace 1966 with your $_GET variable. i.e.

array_search($_GET['delete'], $data)

And the $data array would be a list of all your valid product IDs, that you could pull out from your database, or wherever you are storing them.

If you want to re-base the key indexes after this you can do:

$data = array_values($data);

What the above does is fixes the array key indexes, when you unset an element it will be removed from the array, but all keys will maintain their current indexes. So the array indexes may progress like so: 0, 1, 3, 4. If you re-base the array with the above they'll progress naturally again: 0, 1, 2, 3.

Hope that helps, any questions just let me know.

Mikey
  • 2,606
  • 1
  • 12
  • 20