tags:

views:

122

answers:

2

I have an array within an array.

$a = array ( 0 => array ( 'value' => 'America', ), 1 => array ( 'value' => 'England', ), )

How do I check if 'America' exists in the array? The America array could be any key, and there could be any number of subarrays, so a generalized solution please.

Looking on the php manual I see in_array, but that only works for the top layer. so something like in_array("America", $a) would not work.

Thanks.

+6  A: 

A general solution would be:

function deep_in_array($needle, $haystack) {
    if(in_array($needle, $haystack)) {
        return true;
    }
    foreach($haystack as $element) {
        if(is_array($element) && deep_in_array($needle, $element))
            return true;
    }
    return false;
}

The reason why I chose to use in_array and a loop is: Before I examine deeper levels of the array structure, I make sure, that the searched value is not in the current level. This way, I hope the code to be faster than doing some kind of depth-first search method.


Of course if your array is always 2 dimensional and you only want to search in this kind of arrays, then this is faster:

function in_2d_array($needle, $haystack) {
    foreach($haystack as $element) {
        if(in_array($needle, $element))
            return true;
    }
    return false;
}
Felix Kling
way to goooo !!
Jhonny D. Cano -Leftware-
I think the `return` after `if(is_array...)` is problematic. You cannot do a return for each element. Instead you should only return if call to `deep_in_array` returns true.
middus
My array is always two dimensional. I love how both answers are named felix. :) Is your second option faster than the other felix's?
Mark
@middus: Your are right, didn't realize that. Thank you very much!
Felix Kling
Hehe, actually I'm also "a Felix". The other Felix' answer is a general solution, not a two dimensional one.
middus
@Mark: It depends on the structure of your array. Probably yes.
Felix Kling
@middus: LOL, today is Felix day or what? ;) Btw my first code example is also general ;)
Felix Kling
Recursion makes me happy! It just gives me a warm and fuzzy feeling. Have another upvote!
Buggabill
Felixes around the world, rejoice! =)
Felix
+4  A: 

PHP doesn't have a native array_search_recursive() function, but you can define one:

function array_search_recursive($needle, $haystack) {
    foreach ($haystack as $value) {
        if (is_array($value) && array_search_recursive($needle, $value)) return true;
        else if ($value == $needle) return true;
    }
    return false;
}

Untested but you get the idea.

Felix
Hey Felix ;) Could be faster than mine because you traverse the array only once. On the other side you will always examine the arrays first although the search value might already exists in the current array level.
Felix Kling