1

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 I tried to search and tested a lot but doesn't found what I need. I Hope someone of you can help me!

Jason Schilling
  • 475
  • 6
  • 19
  • Try checking this http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array – Sasikumar Sep 14 '16 at 09:17
  • @Sasikumar that doesn't work, I already tried this and it also doesn't fit my goal. – Jason Schilling Sep 14 '16 at 09:19
  • Possible duplicate of [how to check one array is exact subset of another array - php array](http://stackoverflow.com/questions/12276565/how-to-check-one-array-is-exact-subset-of-another-array-php-array) – Martin Nyolt Sep 14 '16 at 10:07

2 Answers2

1
$cnt = 0;
    foreach ($second_array as $key => $value) {
            foreach ($first_array as $key_1 => $value_1) {
                if($key == $key_1){
                    $cnt++;
                }
            }
    }

    if($cnt > 0){
        echo "second array element in first array";
    }else{
        echo "not in array";
    }
  • I see what you tried, a good approach, but it doesn't fit if the second array is `[ 'group' => [ 'list' => FALSE ] ]` – Jason Schilling Sep 14 '16 at 09:26
  • 1
    $cnt = 0; if(count($second_array) > 0){ foreach ($second_array as $key => $value) { if(count($first_array) > 0){ foreach ($first_array as $key_1 => $value_1) { if($key == $key_1){ $cnt++; } } } } } – Jignesh Prajapati Sep 14 '16 at 09:30
0

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;
}
Jason Schilling
  • 475
  • 6
  • 19