How to remove all PHP array elements containing a

2020-04-10 03:13发布

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

3条回答
三岁会撩人
2楼-- · 2020-04-10 03:28

The simplest way is with array_filter. This function receives the array to filter and a callback function that does the actual filtering based on the value received:

function filter_func( $v )
{
  return ( ( $var % 2 ) == 0 );
}
$test_array = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );
print_r( array_filter( $test_array, "filter_func" ) );

Hope helped!

查看更多
叼着烟拽天下
3楼-- · 2020-04-10 03:31

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); }));
查看更多
家丑人穷心不美
4楼-- · 2020-04-10 03:32

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)

查看更多
登录 后发表回答