It isn’t quite obvious to remove an array item when all you know is the value of that item, – i.e. you don’t now the item index.
Remove items without preserving original indexes
$the_array = array_values(array_diff($the_array,array($the_value))); // Example $the_array = array('A', 'B', 'B', 'C'); $the_array = array_values(array_diff($the_array,array('B'))); /* Original array: [0] => A [1] => B [2] => B [3] => C After removing 'B': [0] => A [1] => C */
Remove items and preserve indexes
Based on Tobias code
while($key = array_search($the_value, $the_array)){unset( $the_array[$key]);} // Example $the_array = array('A', 'B', 'B', 'C'); while($key = array_search('B', $the_array)){unset( $the_array[$key]);} /* Original array: [0] => A [1] => B [2] => B [3] => C After removing 'B': [0] => A [3] => C */
There is an other possibility:
With this code, the keys are preserved.
This was exactly the solution I was looking for. Thank you 🙂
Greetings,
Benni
Nice, but the problem is that it removes only the first occurrence of $the_value, I used your code and added a loop to remove all occurrences.