Search code examples
phparraysmultidimensional-arrayfilterarray-difference

Check if a 2d array doesn't have any values in another 2d array


I am using the following code to find if $devices_ForUser doesn't have any values listed in $device_CurrentIDS.

$results = array_diff($devices_ForUser, $device_CurrentIDS);

When I check if $results is empty, it shows as empty when it should not be empty.

$device_CurrentIDS = [
    ["0x0000000000000013620010713E5A"],
    ["0x000000000000001077002942CE57"],
    ["0x20120427850602000103026906B2"],
    ["0xE20062969619018824701915D683"],
    ["0x0000000008002216572D06103CF6"],
    ["0xE2004465650F015224401B255262"],  // found in the other array
    ["0xE20092012053100000002850D14E"],
    ["0x300833B2DDD901400000000039BB"],
    ["0xE2002996961802570960B3F06912"],
    ["0x000000000000000000501420B8B6"],
    ["0x201203298478040001020252A5EC"],
    ["0xE20010008007026819204FCAF906"],
    ["0x0000000000000000000007485DF6"],
    ["0xE2001036990F008812908EA5481C"],
    ["0x0019000000000000000043B94C3A"],  // found in the other array
    ["0x0000000000000000004004490529"],  // found in the other array
    ["0x0000000000000000000010066E18"],  // found in the other array
    ["Error 0100: syntax error at ''"],
    ["Error 0102: Error performing query"],
    [null]
];

and

$devices_ForUser = [
    ["0x0019000000000000000043B94C3A"],
    ["0x0000000000000000004004490529"],
    ["0x0000000000000000000010066E18"],
    ["0xE2004465650F015224401B255262"]
];

Solution

  • see http://uk.php.net/manual/en/function.array-diff.php :

    This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

    You have a nested array, this cant work.

    EDIT:

    This may work:

    function array_values_recursive($ary)
    {
       $lst = array();
       foreach( array_keys($ary) as $k ){
          $v = $ary[$k];
          if (is_scalar($v)) {
             $lst[] = $v;
          } elseif (is_array($v)) {
             $lst = array_merge( $lst,
                array_values_recursive($v)
             );
          }
       }
       return $lst;
    }
    
    $result = array_diff(array_values_recursive($devices_ForUser), array_values_recursive($device_CurrentIDS));
    var_dump($result);