Roland Roland - 1 year ago 68
PHP Question

PHP compare two arrays and get the difference

I have two arrays

$original = array(
array('fruit' => 'appel','color' => 'green'),
array('fruit' => 'Banana','color' => 'Yellow'),
array('fruit' => 'orange','color' => 'orange',)


$new = array(
array('fruit' => 'appel'),
array('fruit' => 'orange')

Now i want to compare the two arrays and print out the different one.
In this case i want to keep

array('fruit' => 'Banana','color' => 'Yellow')

When i use array_intersect_key

$original_new = array_intersect_key($new, $original);

it's deleting the array i want to keep.
I thought i do this:

$original_new = array_intersect_key($new, $original);
$original_new = array_diff($original_new, $original);

But this is of course not working.
Can somebody help me out whit this?

Answer Source

Using some loop and array. Check Online.

First make the array from $new array with the column only, and using the foreach loop over the $original array just check the fruit is in the $new array or not, if not than store the complete sub array in an array name $arr.

$arr = array();
$com = array_column($new, 'fruit');
foreach($original as $value){
    if(!in_array($value['fruit'], $com)){
        $arr[] = $value;

print_r($arr); //Array ( [0] => Array ( [fruit] => Banana [color] => Yellow ) )