Skip to content
Advertisement

PHP compare arrays and remove NOT matched objects

I want to compare two arrays with each other and remove all objects from the first one who are NOT present in both arrays.

    //array1
    $apiData1 = [
       'test1' => ["Volvo", "BMW", "Toyota"],
       'test2' => ["Volvo", "BMW", "Toyota"],
       'test3' => ["Volvo", "BMW", "Toyota"],
       'test4' => ["Volvo", "BMW", "Toyota"],
       'AAAAAAAAAAAAAAA' => ["Volvo", "BMW", "Toyota"],
    ];

    // ======================

    //array2
    $apiData2 = [
       'test1' => ["Volvo", "BMW", "Toyota"],
       'test2' => ["Volvo", "BMW", "Toyota"],
       'test3' => ["Volvo", "BMW", "Toyota"],
       'test4' => ["Volvo", "BMW", "Toyota"],
       'BBBBBBBBBBBBBBB' => ["Volvo", "BMW", "Toyota"],
    ];

The result should be array1 without the ‘AAAAAAAAAAAAAAA’ object.

//array1
$apiData1 = [
   'test1' => ["Volvo", "BMW", "Toyota"],
   'test2' => ["Volvo", "BMW", "Toyota"],
   'test3' => ["Volvo", "BMW", "Toyota"],
   'test4' => ["Volvo", "BMW", "Toyota"],
];

What I tried:

foreach ($apiData2 as $key => $value) {

    if ((isset($apiData1[$key]) && !isset($apiData2[$key])) || (!isset($apiData1[$key]) && isset($apiData2[$key]))) {

        unset($apiData1[$key]);

    }

}

Advertisement

Answer

array_intersect_key is what you’re looking for. It takes two or more arrays, and returns a new array containing the elements of the first array, whose keys are present in all provided arrays.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement