Say this is your $_SESSION['basket']
:
Array
(
[0] => Array
(
[id] => 12
[name] => some name
[color] => some color
)
[1] => Array
(
[id] => 8
[name] => some name
[color] => some color
)
[2] => Array
(
[id] => 3
[name] => some name
[color] => some color
)
[3] => Array
(
[id] => 22
[name] => some name
[color] => some color
)
)
First you need to loop through all the individual elements of the array $_SESSION['basket']
:
foreach ($_SESSION['basket'] as $i => $product) {
/*
$i will equal 0, 1, 2, etc.
and is the position of the product within the basket array.
$product is an array of itself, which will equal e.g.:
Array
(
[id] => 12
[name] => some name
[color] => some color
)
*/
}
Now you want to know if the id
of a product matches the ID of the product you're looking for. You don't need to go through every element of the $product
array to do that, assuming your ID will always be named "id". Simply check the id
field instead:
foreach ($_SESSION['basket'] as $i => $product) {
if ($product['id'] == $someId) {
// at this point you want to remove this whole product from the basket
// you know that this is element no. $i, so unset it:
unset($_SESSION['basket'][$i]);
// and stop looping through the rest,
// assuming there's only 1 product with this id:
break;
}
}
Notice that there's also a danger to checking the values, and not the keys. Say you have a product that's build up like so:
Array
(
[count] => 12
[id] => 5
[name] => some name
[color] => some color
)
If you go through all the values, like your doing now, and try to match that to a certain id, what happens when this id happens to be "12"?
// the id you're looking for:
$someId = 12;
foreach ($product as $key => $value) {
// first $key = count
// first $value = 12
if ($value == $someId) {
// ...
// but in this case the 12-value isn't the id at all
}
}
So: always reference a specific element from the array, in this case "id" (or whatever the name is that you used in your app). Don't check random values, since you can't be absolutely certain that when it matches, this is in fact the correct value you're looking for.
Good luck!