Finding a PHP array in an array

$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 fact, the array is stringsreally huge (50k + entries).

What is the best way to start searching and highlight matching strings only ?

+4
source share
2 answers

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;
}
+3
source

Use array_filterto filter an array $strings.
Separate the lines into an array, then trim each word and use array_intersectto 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);
});
+3
source

Source: https://habr.com/ru/post/1621881/


All Articles