I'm nidhin
I'm nidhin

Reputation: 2662

PHP: search array with similar matching keywords

I have an array like

$arr = array(0 => array(id=>1,name=>"Apple"),
             1 => array(id=>2,name=>"Orange"),
             2 => array(id=>3,name=>"Grape")
);

I have written the code for searching the multidimensional array.

Here is it

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}

But it works only for exactly matching keywords. What I need is, If I search for 'Gra' in this array. The function should return

array(0 => array(id=>1,name=>"Grape")
);

This seems to be something like mysql %LIKE% condition.How can this be done in PHP arrays ?

Upvotes: 0

Views: 139

Answers (3)

Jim
Jim

Reputation: 22646

When checking if the string matches you can instead use strpos

strpos($strToCheck, 'Gra') !== false;//Will match if $strToCheck contains 'Gra'

strpos($strToCheck, 'Gra') === 0;    //Will match if $strToCheck starts with 'Gra'

Note that the above is case sensitive. For case insensitivity you can strtoupper both strings before comparing use strripos instead.

In your example the check would become:

if (isset($array[$key]) && strpos($array[$key],$value) !== false) {
    $results[] = $array;
}

Upvotes: 2

Vahe Shadunts
Vahe Shadunts

Reputation: 1966

You can use stristr function for string manipulations in php, and you'll don't have to think about different cases and cast them to uppercase.

stristr function is not case sensitive, so your code will like this

 if (isset($array[$key]) && stristr($array[$key], $value) !== false) {
        $results[] = $array;
 }

Upvotes: 1

Sujit Agarwal
Sujit Agarwal

Reputation: 12508

Focussing on the line here that you wrote -

if (isset($array[$key]) && $array[$key] == $value) {

We can modify it to search for substrings, rather than exact match -

if (isset($array[$key]) && strpos($array[$key], $value)) {

This will try to find if the value is present somewhere in the content of $array[$key]

Hope it helps

Upvotes: 0

Related Questions