Php array recursive analysis - find value

I have an nxn array that is recursively trying to get a specific value based on the following:

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

How could I achieve this? Thanks

An example of what the array looks 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
                )
    )
+3
source share
1 answer

the function I'm using ...

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

Hope you enjoy it and use it: D have a nice day!

+2
source

All Articles