Search code examples
phparraysrecursionmultidimensional-array

Test if a value exist in a multidimensional array whether as a key or a value


Let's take this array as an example:

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'vegetable' => array(
        'carrot' => 'carrot2',
    ),
    'fruits' => 'fruits',
);

Now how to do a general search to check if a value exists whether as a key or a value in the array and his sub-arrays.


Solution

  • I think we may use a double control

    if(multi_array_key_exists($needle, $haystack)||deep_in_array($needle, $haystack))
    {
        //Value exists
    }
    

    multi_array_key_exists function:

    function multi_array_key_exists( $needle, $haystack ) { 
    
        foreach ( $haystack as $key => $value ) : 
    
            if ( $needle == $key ) 
                return true; 
    
            if ( is_array( $value ) ) : 
                 if ( multi_array_key_exists( $needle, $value ) == true ) 
                    return true; 
                 else 
                     continue; 
            endif; 
    
        endforeach; 
    
        return false; 
    }
    

    Source: http://www.php.net/manual/en/function.array-key-exists.php#92355

    deep_in_array function:

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

    Source: php Checking if value exists in array of array