Forum Moderators: coopster
I made a small shopping cart function that adds/removes item in a session array.
It adds/removes items perfectly inside the session, but when I try to display it out I tried something like
$count = count($_SESSION['cart']);
and made a for loop $i = 0; $i < $count; $i++ and displayed things out.
Problem is, when I completely remove an item in between, then the keys doesn't get rearranged, so the loop doesn't really work.
Example would be..
Add 2 socks
Add 3 tires
Add 2 shoes
would give me
[0] => 2 socks
[1] => 3 tires
[2] => 2 shoes
and loop would just go through 0 through 2.
but if i take 3 tires out..
[0] => 2 socks
[2] => 2 shoes
booom! its broken.
I tried:
while(list($key, $val) = each($cart)) {
displayItem($cart['item'][$key], $cart['qty'][$key]);
}
Any suggestions?
//first find the position in the array of the item you want to delete from cart
//second, make it null
//use a loop and assign the entire cart to a temp array skipping only the null values. i had a double array to store my items (item id, amount) so my loop is a litle different than the one i came up below.
$counter = 0;
for($i=0; $i<sizeof($cart); $i++){
if($cart[$i]!= null){
$temp[$counter] = $cart[$i];
}
}
//assign the temp array back to the cart session