My shopping basket is an array and each item in it is also an array.
At some points I am looping through each item looking for ID matches. When I have a match, I need to know the Items position in the main basket array so that i can perform updates and deletes.
Sounds very simple but I’m stuck on it.
I have this so far
//Lets say there are 5 items in this basket array (each item is also an array)
foreach ($_SESSION['basket'] as $basketArray){
//this loops through the items attributes (size, colour etc)
//when the ID is a match, i need to find out what position I am at in the main array
foreach($basketArray at $key = > $value){
if ($value == $itemID){
//now I just need to know how to return 0, 1, 2, 3, or 4 so that i can do 'unset' later.
}
}
}
Thanks for any help.
Ozzy
Say this is your
$_SESSION['basket']:First you need to loop through all the individual elements of the array
$_SESSION['basket']:Now you want to know if the
idof a product matches the ID of the product you’re looking for. You don’t need to go through every element of the$productarray to do that, assuming your ID will always be named “id”. Simply check theidfield instead: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:
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”?
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!