Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search a php array for partial string match [duplicate]

I have an array and I'd like to search for the string 'green'. So in this case it should return the $arr[2]

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red'); 

is there any predefined function like in_array() that does the job rather than looping through it and compare each values?

like image 254
ralixyle Avatar asked Apr 11 '13 09:04

ralixyle


1 Answers

For a partial match you can iterate the array and use a string search function like strpos().

function array_search_partial($arr, $keyword) {     foreach($arr as $index => $string) {         if (strpos($string, $keyword) !== FALSE)             return $index;     } } 

For an exact match, use in_array()

in_array('green', $arr) 
like image 142
n a Avatar answered Sep 16 '22 19:09

n a