phparraysfilterprefixblacklist

Filter a flat array by removing elements whose substring before the first occurring dot is found in a blacklist array


I have an array that looks like this:

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

and I want delete the value with other in the value.

I tried to use array_filter() to filter this word, but array_filter() will delete all the empty values too.

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?


Solution

  • foreach($sport_level_name_arr as $key => $value) {
      
      if(in_array($value, $bad_words)) {  
        unset($sport_level_name_arr[$key]);
      }
    
    }