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?

Anders Hedeager
  • 107
  • 2
  • 8
  • 1
    possible duplicate of [How to delete object from array inside foreach loop?](http://stackoverflow.com/questions/2304570/how-to-delete-object-from-array-inside-foreach-loop) – gd1 Jan 13 '13 at 21:51

3 Answers3

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!

Jeroen
  • 13,056
  • 4
  • 42
  • 63
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])
   }
}
Ayush
  • 41,754
  • 51
  • 164
  • 239
  • `for ($arr as $key => $val)` would be better since your answer is limited to non-associative arrays. – Corbin Jan 13 '13 at 21:53
1

try something like:

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