0

Simple question; How can i delete the right Array from my foreach() ?

foreach ( $items as $e):
    if ( $e['seat'] == $users[$clientID]['seat']):
        //It's done, delete it.
        unset ( $e );
    endif;
endforeach;

unset($e) doesn't seem to work properly. What is the right solution to delete the right array from the right index?

1

3 Answers 3

4

This is an alternative to the for-loop given by xbonez, by passing the key value as well:

foreach ( $items as $key => $e):
    if ( $e['seat'] == $users[$clientID]['seat']):
        //It's done, delete it.
        unset ( $items[$key] );
    endif;
endforeach;

I prefer this version, but it doesn't really matter!

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

Comments

1

Doing unset($e) in a foreach unsets the variable $e, not the item in the array that it represents. You would need to use a a regular for-loop for this

for($i = 0; $i < count($items); $i++) {
   if ($items[$i]['seat'] == $users[$clientID]['seat']) {
      unset($items[$i])
   }
}

1 Comment

for ($arr as $key => $val) would be better since your answer is limited to non-associative arrays.
1

try something like:

foreach ($items as &$e):
    if ($e['seat'] == $users[$clientID]['seat']):
        //It's done, delete it.
        unset ($e);
    endif;
endforeach;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.