Search code examples
phparrayssubstringfilteringarray-filter

Filter out array values that do not contain a specified substring


I would like to know how can I filter an array to remove values that do not contain a specified string?

Example:

$array = ['January', 'February', 'March', 'April'];
$to_search = "uary"; // not case sensitivity
$result = somefunction($array, $to_search );
print_r($result);

The expected output is:

$result = ['January', 'February'];

I hope to use the most efficient and fastest way in searching among the arrays because the array that I might use contains at least 100 items.


Solution

  • DEMO

    You should choose array_filter function. e.g.

    $to_search = "uary"; // not case sensitivity
    $array = array('January', 'February', 'March', 'April');
    
    $result = array_filter($array, function ($item) use ($to_search ) {
     if (stripos($item, $to_search ) !== false) {
        return true;
     }
    return false;
    });
    

    and to get and display your array, use the var_dump

    var_dump($result);
    

    Please try with this and let me know.