$keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');
$strings = array(
'She had a pink dress',
'I have a white chocolate',
'I have a green balloon',
'I have a chocolate shirt',
'He had a new yellow book',
'We have many blue boxes',
'I have a magenta tie');
In reality the strings
array is really huge (50k+ entries).
What is the best way of running search and extracting the matching strings only?
1. PHP array_search() function. The PHP array_search() is an inbuilt function that is widely used to search and locate a specific value in the given array. If it successfully finds the specific value, it returns its corresponding key value.
The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned. Syntax: array_search($value, $array, strict_parameter)
Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.
Use array_filter
to filter the $strings
array.
Split the strings into an array, then trim each word, and use array_intersect
to check if the array of words contains any of the $keywords
.
$result = array_filter($strings, function($val) use ($keywords) {
return array_intersect( array_map('trim', explode(' ', $val)) , $keywords);
});
The best way is to use array_filter()
.
$filtered_array = array_filter($strings,'filter');
function filter($a)
{
$keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');
foreach ($keywords as $k)
{
if (stripos($a,$k) !== FALSE)
{
return TRUE;
}
}
return FALSE;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With