Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for PHP array element containing string [duplicate]

Tags:

arrays

php

$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".

like image 968
UserIsCorrupt Avatar asked Sep 07 '12 09:09

UserIsCorrupt


2 Answers

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.

like image 52
Aleks G Avatar answered Sep 23 '22 02:09

Aleks G


function customSearch($keyword, $arrayToSearch){     foreach($arrayToSearch as $key => $arrayItem){         if( stristr( $arrayItem, $keyword ) ){             return $key;         }     } } 
like image 22
Wayne Whitty Avatar answered Sep 21 '22 02:09

Wayne Whitty