4

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
        )

)
3
  • 1
    you can use !strcmp($val1['age'], $val2['age']); Commented Jul 28, 2015 at 7:10
  • Check this post: stackoverflow.com/questions/12169821/… Commented Jul 28, 2015 at 7:14
  • 1
    Your compareDeepValue has 3 return statements. Only first is reachreachable. Commented Jul 28, 2015 at 7:15

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Kleskowy, I really liked this one but just FYI this would just print the unmatched array in Main Array 1 & not the corresponding unmatched array in Main array 2.
@WisdmLabs sure, just as all array_diff functions would. Doing it again with arrays passed in reversed order and you have all unmatching results.
3
Your Arrays:

$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' ),
        );



foreach($arr1 as $key=>$arr)
{
 $bool = true; 
 $ar1 = $arr;
 $ar2 = $arr2[$key];

 foreach($ar1 as $ky=>$val)
{
  if($val != $ar2[$ky])
  {
    $bool = false;
    break;
  }
}

 if(!$bool)
{
  echo "Unmatched Arrays: \r\n";
  print_r($ar1); echo " in  Main Array 1 &  \r\n";
  print_r($ar2); echo " in  Main Array 2. \r\n";
}

}

2 Comments

Dear, the boolean condition wasn't proper. Try now! Thanks!
@maxcheng This probably works with data provided with the example, but IMHO comparisons are weak here and this code is not that re-usable. Check out my answer if you like.
2

try this one

$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' ),
    );


$tmpArray = array();

 foreach($arr1 as $data1) {

  $duplicate = false;
   foreach($arr2 as $data2) {
    if($data1['name'] === $data2['name'] && $data1['age'] === $data2['age'] && $data1['country'] === $data2['country']) $duplicate = true;
    }

 if($duplicate === false) $tmpArray[] = $data1;
 }
 echo "<pre>", print_r($tmpArray);

Comments

2
$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
print_r($intersect);
// add this and it will return the missing array.
print_r(array_diff_key($arr1, $intersect));

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

Comments

0

I would like to give you another possible solution. I've checked the code and it seems to fit your needs.

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

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

    /** @var array $notMatched */
    $notMatched = array();
    /**
     * @var int   $index
     * @var array $element
     */
    foreach($arr1 as $index => $element) {
        /**
         * @var string $key
         * @var string $value
         */
        foreach($element as $key => $value) {
            if($arr2[$index][$key] !== $value) {
                $notMatched["arr1"] = $arr1[$index];
                $notMatched["arr2"] = $arr2[$index];
            }
        }
    }
    if(!empty($notMatched)) {
        echo "Unmatched arrays: \r\n";
        echo "Array 1:\r\n";
        print_r($notMatched["arr1"]);
        echo "Array 2:\r\n";
        print_r($notMatched["arr2"]);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.