PHP: remove an array item by value

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
*/

3 thoughts on “PHP: remove an array item by value”

  1. There is an other possibility:

    $key = array_search($the_value, $the_array);
    if( $key !== false ){
        unset( $the_array[$key] );
    }
    

    With this code, the keys are preserved.

    1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top