We have an array, for example:
$my_array = array(
'Software Engineering',
'Civil Engineering',
'Hardware Engineering',
'BL AH Engineering'
);
Now I have a "$q" variable, I want to search between values of the array, remove the keys which doesn't contain $q, here is my code:
foreach ($my_array as $key => &$value) {
if (stripos(($value), $q) === false) {
unset($my_array[$key]);
}
}
now if we set the $q = 'eer':
var_dump($my_array);
array
0 => string 'Software Engineering' (length=20)
1 => string 'Civil Engineering' (length=17)
2 => string 'Hardware Engineering' (length=20)
3 => &string 'BL AH Engineering' (length=17)
as you see, nothing is removed since all the $values have 'eer' in 'Engineering'
it's OK, but now I set $q = 'eer civil'
, now:
var_dump($my_array);
array
empty
All the items are removed, but actually the 'Civil Engineering' contains both the 'eer' and 'civil', so it should not be removed, how I could make this work? I may explode the $q with ' space ' but it's not working.
Using explode
should work:
Update
Use preg_split
and trim
to get rid of multiple/leading/trailing delimiters.
$array = array('Software Engineering', 'Civil Engineering', 'Hardware Engineering', 'BL AH Engineering');
$query = ' eer civil ';
$query = preg_split('/\s+/', trim($query));
foreach ($array as $key => $value) {
foreach ($query as $q) {
if (stripos($value, $q) === false) {
unset($array[$key]);
break;
}
}
}
var_dump($array);