6

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?

2

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

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

}

2 Comments

This doesn't renumber the array like the OP wanted.
Hey EdoDodo Just need use php function "array_values",
2

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

array_values(array_diff($arr,array("other")));

2 Comments

it will create two array and will find the diffrence, in the second array the we will put the elements to exclude
Notice that the asker's coding attempt is more nuanced. The required implementation needs to match the leading portion of each array value against an array of blacklisted prefixes.
0

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

So you need to do return true; in your filter(); function instead of return $element; to make sure that no empty values are removed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.