phparraysfilterkeyarray-difference

How to compare keys in one array with values in another, and return non-matches?


I have multidimensional array:-

$first= array(
    [51581481] => array(
        'title' => 'Nike - L',
        'price' => '300.00',
        'vendor' => 'Vicky Fashion Point',
        'quantity' => -23,
    ),
    [45747894] => array(
        'title' => 'Honor Band A (Black) - Default Title',
        'price' => '2249.00',
        'vendor' => 'Honor',
        'quantity' => 8,
    )
);
$second = array(
    0 => '45747894',
    1 => '713776113',
);

I want to compare both array and get difference data from array first. I am using array_diff function

$arr_diff= array_diff($first, $second);

This Error show:-

ERROR: Array to string conversion 

Solution

  • Like that

    $arr_diff  = array_diff_key($first, array_flip($second));
    

    the trick is to array_flip the second array and use array_diff_key

    Working example

    $first = array(
        51581481 => array(
            'title' => 'Nike - L',
            'price' => '300.00',
            'vendor' => 'Vicky Fashion Point',
            'quantity' => -23,
        ),
        45747894 => array(
            'title' => 'Honor Band A (Black) - Default Title',
            'price' => '2249.00',
            'vendor' => 'Honor',
            'quantity' => 8,
        ),
    );
    $second = array(
        0 => 45747894,
        1 => 713776113,
    );
    
    
    var_dump(array_diff_key($first, array_flip($second)));