How to search in PHP Array, similar to MySQL Like %var% search
$needle="bob";
$output=array();
foreach($array as $k=>$v)
{
if(stristr($k,$needle) || stristr($v,$needle))
$output[$k]=$v;
}
print_r($output);
Fiddle
That is if you want to search keys and values both, Remove the keys part if you just want to search values.
Here is a preg_grep
solution that should work more like a WHERE REGEXP 'PATTERN'
in MySQL. I modified Daniel Klein's preg_grep_keys
function to search for the pattern within array keys, and added an array_merge
to it, which should work with the arrays with non-numeric keys. If the keys are numeric, just use a mere preg_grep
solution (preg_grep('~Mark~i', $arr);
to find all array elements having mark
or Mark
, etc.).
array_merge
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
function preg_grep_keys_values($pattern, $input, $flags = 0) {
return array_merge(
array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags))),
preg_grep($pattern, $input, $flags)
);
}
$a = array(
'[email protected]'=> "Mark Mian lv",
'[email protected]'=> "John jack lv",
'[email protected]'=> "Bob Logon",
'[email protected]'=> "Stela Josh",
'[email protected]'=> "Json Josh",
'[email protected]'=> "Bob Mark"
);
$r = preg_grep_keys_values('~lv~i', $a);
print_r($r);
See this IDEONE demo
The code above searches for lv
(case-insensitively) in the keys first, then in the values, and then merges the results into 1 array. Thus, the results are:
[[email protected]] => John jack lv
[[email protected]] => Bob Mark
[[email protected]] => Mark Mian lv
An easy approach would be to use array_filter
If you want regex's, this would work
$regex = '~test~';
$result = array_filter($data, function($item) use ($regex) {
return preg_match($regex, $item);
});
Or just a simple contains search
$search = 'test';
$result = array_filter($data, function($item) use ($search) {
return stristr($value, $search);
});
If you have to search for both - key and value, you could append the parameter ARRAY_FILTER_USE_BOTH
to array_filter.
$search = 'test';
$result = array_filter($data, function($item, $key) use ($search) {
return stristr($value, $search) || stristr($key, $search);
}, ARRAY_FILTER_USE_BOTH);
And finally, you could combine array_filter with preg_grep to search for both at once.
$search = '~bob~i';
$result = array_filter($data, function() use ($search) {
return count(preg_grep($search, func_get_args()));
}, ARRAY_FILTER_USE_BOTH);