phparrays

Search for PHP array element containing string


$example = array('An example','Another example','Last example');

How can I do a loose search for the word "Last" in the above array?

echo array_search('Last example',$example);

The code above will only echo the value's key if the needle matches everything in the value exactly, which is what I don't want. I want something like this:

echo array_search('Last',$example);

And I want the value's key to echo if the value contains the word "Last".


Solution

  • To find values that match your search criteria, you can use array_filter function:

    $example = array('An example','Another example','Last example');
    $searchword = 'last';
    $matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
    

    Now $matches array will contain only elements from your original array that contain word last (case-insensitive).

    If you need to find keys of the values that match the criteria, then you need to loop over the array:

    $example = array('An example','Another example','One Example','Last example');
    $searchword = 'last';
    $matches = array();
    foreach($example as $k=>$v) {
        if(preg_match("/\b$searchword\b/i", $v)) {
            $matches[$k] = $v;
        }
    }
    

    Now array $matches contains key-value pairs from the original array where values contain (case- insensitive) word last.