Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all PHP array elements containing a certain sub-string?

ok i looked up some functions and i don't seem to lucky of finding any,

i wanna filter an array to strip specific array that contains some string

heres an example :

$array(1 => 'January', 2 => 'February', 3 => 'March',);
$to_remove = "Jan"; // or jan || jAn, .. no case sensitivity
$strip = somefunction($array, $to_remove);
print_r($strip);

it should return

[1] => February
[2] => March

a function that looks for the sub-string for all values in an array, if the sub-string is found, remove that element from the array

like image 640
Lili Abedinpour Avatar asked Dec 06 '22 14:12

Lili Abedinpour


2 Answers

You can use array_filter and stripos

$array = array(1 => 'January', 'February', 'March');
print_r(array_filter($array, function ($var) { return (stripos($var, 'Jan') === false); }));
like image 93
mpratt Avatar answered Dec 10 '22 12:12

mpratt


You can use array_filter() with a closure (inline-function):

array_filter(
  $array,
  function ($element) use ($to_remove) {
    return strpos($element, $to_remove) === false;
  }
);

(PHP Version >= 5.3)

like image 30
MonkeyMonkey Avatar answered Dec 10 '22 13:12

MonkeyMonkey