search a php array for partial string match [duplicate]
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)
There are several ways...
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
Search the array with a loop:
$results = array();foreach ($arr as $value) { if (strpos($value, 'green') !== false) { $results[] = $value; }}if( empty($results) ) { echo 'No matches found.'; }else { echo "'green' was found in: " . implode('; ', $results); }
Use array_filter():
$results = array_filter($arr, function($value) { return strpos($value, 'green') !== false;});
In order to use Closures with other arguments there is the use
-keyword. So you can abstract it and wrap it into a function:
function find_string_in_array ($arr, $string) { return array_filter($arr, function($value) use ($string) { return strpos($value, $string) !== false; });}$results = find_string_in_array ($arr, 'green');if( empty($results) ) { echo 'No matches found.'; }else { echo "'green' was found in: " . implode('; ', $results); }
Here's a working example: http://codepad.viper-7.com/xZtnN7