Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi I am trying to remove an array element using a foreach loop, but it is not doing anything. I need the index to be completely gone rather than making it null. Here is what I have tried:

foreach ($_SESSION['cart']  as &$arrays3) {
if($arrays3['id'] == $id){
unset($arrays3);
}
}

Note, the array value for each key contains an associative array.

share|improve this question

2 Answers

up vote 2 down vote accepted

You need to use the key from your foreach, and unset the variable directly (from the session):

foreach ($_SESSION['cart']  as $key => $arrays3) {
    if($arrays3['id'] == $id){
        unset($_SESSION['cart'][$key]);
    }
}

Unsetting $arrays3 or any of its children will only be effective until the next iteration of the foreach loop, when it will be set again.

share|improve this answer
 
In the same loop I will be modifying some elements, so should I not use the '&' before arrays3? –  Matt9Atkins Oct 15 at 23:39
 
safer to refer directly to them: $_SESSION['cart'][$key]['your_index'] = 'your_value'; –  scrowler Oct 15 at 23:40
 
or do as @Sven suggests in his answer below... –  scrowler Oct 15 at 23:40

You are using a dangerous form of the foreach loop. You MUST always unset the reference variable after the loop:

foreach ($_SESSION['cart']  as &$arrays3) {}
unset($arrays3);

Otherwise things will break if that loop is used again.

And the reference really is not needed. foreach operates on a copy of the array, so changes to the key or value will not go back into the original array, but you can always access the original array, as shown in the answer of @scrowler.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.