Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements in array matching a specific string using PHP

Tags:

arrays

php

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.

like image 857
Craig Wilson Avatar asked Dec 29 '12 02:12

Craig Wilson


2 Answers

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
like image 189
mario Avatar answered Oct 18 '22 15:10

mario


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. 
});
like image 6
Shiplu Mokaddim Avatar answered Oct 18 '22 16:10

Shiplu Mokaddim