PHP, how to filter an array that contains something?

ok I looked at some functions and it seemed to me unlucky to find any,

I want to filter an array to highlight a specific array that contains some string

Here is an example:

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

he must return

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

function that searches for a string in an array if the string found splits the entire array

+3
source share
3 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); }));
+7
source

You can use array_filter () with closure (inline functions):

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

(PHP version> = 5.3)

+3
source

The easiest way is array_filter. This function receives a filter for filtering and a callback function that performs the actual filtering based on the received value:

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!

0
source

All Articles