search a php array for partial string match
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
You can use preg_grep function of php. It's supported in PHP >= 4.0.5.
$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);
$m_array
contains matched elements of array.
PHP 5.3+
array_walk($arr, function($item, $key) {
if(strpos($item, 'green') !== false) {
echo 'Found in: ' . $item . ', with key: ' . $key;
}
});
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)