0

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 ?

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
 }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.