15

I'm hoping this is really simple, and I'm missing something obvious!

I'm trying to remove all elements in an array that match a certain string. It's a basic 1D array.

array("Value1", "Value2", "Value3", "Remove", "Remove");

I want to end up with

array("Value1", "Value2", "Value3");

Why does array_filter($array, "Remove"); not work?

Thanks.

9
  • 2
    Because you're using it incorrectly. php.net/manual/en/function.array-filter.php see examples. Commented Dec 29, 2012 at 2:31
  • 2
    It accepts a callback. array_filter($array, function($a) {return $a !== "Remove";}); Commented Dec 29, 2012 at 2:33
  • I understand the examples use functions, but I don't understand what they are returning? Is there not a simple way to do it without building a handler function? Commented Dec 29, 2012 at 2:33
  • @CraigWilson The simpler way is with a PHP 5.3+ anonymous function as in my comment above. Commented Dec 29, 2012 at 2:34
  • simple, yes, magic not requiring you to do anything - no. Commented Dec 29, 2012 at 2:35

2 Answers 2

25

You can just use array_diff here, if it's one fixed string:

$array = array_diff($array, array("Remove"));

For more complex matching, I'd use preg_grep obviously:

$array = preg_grep("/^Remove$/i", $array, PREG_GREP_INVERT);
// matches upper and lowercase for example
Sign up to request clarification or add additional context in comments.

4 Comments

Regular expressions are usually slower for large data-set.
@shiplu For small data sets moreso. The regex compilation is done just once. Which is where the overhead is. PCRE is oftentimes faster for string processing, in this case possibly also the array processing, as most of it operates in C, not as PHP bytecode in the Zend VM.
Tip: You probably want to use $array = array_values($array); for reindexing, right after array_diff to not run into PHP error warnings of undefined array indices.
Warning/notice: if "Remove" was not found in $array, then it will be added to it. array_diff is orderless and creates an array consisting of entries found in none. Thus, the first line of code acts as a toggle that removes "Removes" if its there or adds it in if it wasnt found.
7

You need to use a callback.

array_filter($array, function($e){
   return stripos("Remove", $e)===false
});

To understand above code properly see this commented code.

array_filter($array, function($e){
    if(stripos("Remove", $e)===false) // "Remove" is not found
        return true; // true to keep it.
    else
        return false; // false to filter it. 
});

1 Comment

The tutorial is appreciated! My IDE complained, so I added a semi-colon: return stripos("Remove", $e)===false;

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.