Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from an array whose value matches a specified string

Tags:

arrays

php

filter

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 try 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?

like image 623
wyman Avatar asked Jul 01 '11 11:07

wyman


2 Answers

foreach($sport_level_name_arr as $key => $value) {

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

}
like image 100
Ēriks Daliba Avatar answered Nov 15 '22 06:11

Ēriks Daliba


array_filter() is the right function. Ensure your callback function has the correct logic.

Try the following:

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

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

Note: if you want to reindex the array, then you could call $new_arr = array_values($new_arr); after the above.

like image 20
Jason McCreary Avatar answered Nov 15 '22 07:11

Jason McCreary