Removing elements from an array whose value matches a given string

I have an array that looks like this:

Array ([0] => Vice President [1] => [2] => other [3] => Treasurer)

and I want to remove the value of c otherin the value.

I am trying to use array_filterto filter this word, but array_filterwill also delete all empty values.

I want the result to be like this:

Array ([0] => Vice President [1] => [2] => Treasurer)

This is my PHP filter code:

function filter($element) {
  $bad_words = array('other');  

  list($name, $extension) = explode(".", $element);
  if(in_array($name, $bad_words))
    return;

  return $element;
}

$sport_level_new_arr = array_filter($sport_level_name_arr, "filter");

$sport_level_new_arr = array_values($sport_level_new_arr);

$sport_level_name = serialize($sport_level_new_arr);

Can I use another method to filter this word?

+5
source share
4 answers
foreach($sport_level_name_arr as $key => $value) {

  if(in_array($value, $bad_words)) {  
    unset($sport_level_name_arr[$key])
  }

}
+3
source

array_filter() . , .

:

function other_test($var) {
    // returns whether the value is 'other'
    return ($var != 'other');
}

$new_arr = array_filter($arr, 'other_test');

:, , $new_arr = array_values($new_arr); .

+3

This will create two arrays and find the difference. In the second array, we exclude the elements:

array_values(array_diff($arr,array("other")));
+2
source

If the callback function returns true, the current value from the input is returned to the result array. PHP manual

Therefore, you need to do return true;in your function filter();instead return $element;to make sure that the empty values ​​are not deleted.

0
source

All Articles