Search code examples
phparraysvalidationrecursionmultidimensional-array

Validate that a multidimensional array is wholly found in another, potentially larger multidimensional array


I got two arrays and want to check if the second array is in the first. The arrays:

First Array:

array(1) {
  ["group"]=>
  array(3) {
    ["create"]=>
    bool(true)
    ["edit"]=>
    bool(true)
    ["delete"]=>
    bool(true)
  }
}

Second Array

array(1) {
  ["group"]=>
  array(1) {
    ["create"]=>
    bool(true)
  }
}

The depth can be different

in_array doesn't work -> array to conversion error and it doesn't mind the assoc allocation.


Solution

  • With the approach from @Jignesh Prajapati I found finally a solution. Thank you!

    function test( $first_array, $second_array ) {
        $found = FALSE;
    
        if( is_bool( $second_array ) && is_bool( $first_array ) ) {
            return $second_array === $first_array;
        }
    
        if( is_array( $first_array ) && is_array( $second_array ) ) {
            foreach( $second_array as $key => $value ) {
                foreach( $first_array as $key_1 => $value_1 ) {
                    if( $key === $key_1 ) {
                        $found = test( $value_1, $value );
                    }
                }
            }
        }
    
        return $found;
    }