Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP compare array and return the different

Tags:

arrays

php

I have two arrays with data in them and I need to compare the two and return the array that are not matched.

I have two arrays that both look like this:

$arr1 = array(
           array('name' => 'Alan', 'age' => '34', 'country' => 'usa'),
           array('name' => 'James', 'age' => '24', 'country' => 'spain' ),
           );

$arr2 = array(
           array('name' => 'Alan', 'age' => '34', 'country' => 'usa'),
           array('name' => 'James', 'age' => '54', 'country' => 'spffain' ),
        );

i would like comparing the array by name,age and country and return me the array that are not matched.

my code so far:

$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
echo "<pre>", print_r($intersect);

function compareDeepValue($val1, $val2)
{
    return strcmp($val1['age'], $val2['age']);
    return strcmp($val1['country'], $val2['country']);
    return strcmp($val1['name'], $val2['name']);

}

The code above return the array that are matched. How can i changed the code in order to get the array that are not matched?

EXPECTED OUTPUT:

Array
(
    [0] => Array
        (
            [name] => James
            [age] => 21
            [country] => spain
        )

)
like image 988
max cheng Avatar asked Dec 25 '22 16:12

max cheng


1 Answers

The code mentioned by someone in answers will work, but it's manual labor :) You could use existing functions to do the job for you. For computing the difference between arrays, you should use array_udiff function (or functions related).

You should write function to compare arrays, and use it to compute the difference, like this:

<?php
$arr1 = array(
       array('name' => 'Alan', 'age' => '34', 'country' => 'usa'),
       array('name' => 'James', 'age' => '24', 'country' => 'spain' ),
       );

$arr2 = array(
       array('name' => 'Alan', 'age' => '34', 'country' => 'usa'),
       array('name' => 'James', 'age' => '54', 'country' => 'spffain' ),
    );

// this function checks if 2 arrays with keys and scalar values are the same
function array_same_check($deepArr1, $deepArr2) {
   //check if arrays are the same
   $diffArr = array_diff_assoc($deepArr1, $deepArr2);
   //if $diffArr has 0 elements - arrays are the same
   if (count($diffArr) === 0) {
      return 0;
   }
   // arrays are not the same - return arbitratry 1 or -1
   return 1;
}

// now let's compare $arr1 and $arr2 you have 
// (meaning: compare the difference between arrays containing arrays) - we use function above
$differing = array_udiff ($arr1, $arr2, 'array_same_check');

print_r($differing);

I copied this code to PHPFiddle and it seems to work as expected.

like image 53
Kleskowy Avatar answered Dec 27 '22 19:12

Kleskowy