Alex Rivera | Logout

Search for PHP array element containing string

Asked 2012-09-07T09:37:25.807
50
$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".

Edit
Report

1 Answer

14
$input= array('An example','Another example','Last example');
$needle = 'Last';
$ret = array_keys(array_filter($input, function($var) use ($needle){
    return strpos($var, $needle) !== false;
}));

This will give you all the keys whose value contain the needle.

answered 2012-09-07T09:45:23.600

Your Answer