Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an nxn array, which recursively I'm trying to get certain value based on the following:

I would like to search for specific value (needle), in this case 'KEYVAL_TO_FIND' if it is found, then, since that part of the array will always have the same structure, I would like to get 'MY_VALUE'.

How could I achieve this? Thanks

An example of how the array look like (ignore the keys):

[0] = Array
    (
        [0] = Array
            (
                [0] = Array
                        [0] = KEYVAL_TO_FIND
                        [1] = Array
                            (
                                [0] = CONST
                                [1] = MY_VALUE
                            )
                    )
        [1] = VAL
        [2] = Array
                (
                   [0] = FOO
                   [1] = BAR BAZ
                )
    )
share|improve this question
    
what have you tried so far? –  Brian Driscoll May 2 '11 at 14:18
    
@Brian Driscoll: I'm not familiar yet w/ recursion –  JoshD May 2 '11 at 14:19
    
@JoshD: Here is a lengthy but understandable article on that topic devzone.zend.com/article/1235 - It's not the easiest programming idiom, but you picked an useful task to experiment with. –  mario May 2 '11 at 14:23
    
possible duplicate of searching within all keys in a multidimensional array PHP –  Alix Axel May 2 '11 at 14:25
    
Thanks everybody! –  JoshD May 2 '11 at 14:26

1 Answer 1

a function I use...

function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }
    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}

I hope you like it and use it :D have a nice day!!

share|improve this answer
    
+1, nice one! - –  Alix Axel May 2 '11 at 14:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.