Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array search within 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 reality the strings array is really huge (50k+ entries).

What is the best way of running search and extracting the matching strings only?

like image 507
Bengali Avatar asked Dec 27 '15 16:12

Bengali


People also ask

How do you get a specific value from an array in PHP?

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.

What is array_search in PHP?

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)

How do you search an array?

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.


2 Answers

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);
});
like image 127
adeneo Avatar answered Oct 19 '22 17:10

adeneo


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;
}
like image 38
worldofjr Avatar answered Oct 19 '22 17:10

worldofjr