1

Hi I am trying to remove an array element using a foreach loop, but it does nothing. 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.

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

In the same loop I will be modifying some elements, so should I not use the '&' before arrays3?
safer to refer directly to them: $_SESSION['cart'][$key]['your_index'] = 'your_value';
or do as @Sven suggests in his answer below...
It's with noting that you can edit the value when iterating by reference but you cannot delete it unless you do so as in the example above
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.