Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare multidimensional arrays in PHP

How can I compare multidimensional arrays in php? Is there a simple way?

like image 961
Kevin Avatar asked Sep 12 '11 14:09

Kevin


3 Answers

The simplest way I know:

$a == $b;

Note that you can also use the ===. The difference between them is:

  1. With Double equals ==, order is important:

    $a = array(0 => 'a', 1 => 'b');
    $b = array(1 => 'b', 0 => 'a');
    var_dump($a == $b);  // true
    var_dump($a === $b); // false
    
  2. With Triple equals ===, types matter:

    $a = array(0, 1);
    $b = array('0', '1');
    var_dump($a == $b);  // true
    var_dump($a === $b); // false
    

Reference: Array operators

like image 85
NullUserException Avatar answered Nov 07 '22 17:11

NullUserException


This function will do it all for you.

You can use it to truly compare any 2 arrays of same or totally different structures.

It will return:

Values in array1 not in array2 (more)

Values in array2 not in array1 (less)

Values in array1 and in array2 but different (diff)

//results for array1 (when it is in more, it is in array1 and not in array2. same for less)
function compare_multi_Arrays($array1, $array2){
    $result = array("more"=>array(),"less"=>array(),"diff"=>array());
    foreach($array1 as $k => $v) {
      if(is_array($v) && isset($array2[$k]) && is_array($array2[$k])){
        $sub_result = compare_multi_Arrays($v, $array2[$k]);
        //merge results
        foreach(array_keys($sub_result) as $key){
          if(!empty($sub_result[$key])){
            $result[$key] = array_merge_recursive($result[$key],array($k => $sub_result[$key]));
          }
        }
      }else{
        if(isset($array2[$k])){
          if($v !== $array2[$k]){
            $result["diff"][$k] = array("from"=>$v,"to"=>$array2[$k]);
          }
        }else{
          $result["more"][$k] = $v;
        }
      }
    }
    foreach($array2 as $k => $v) {
        if(!isset($array1[$k])){
            $result["less"][$k] = $v;
        }
    }
    return $result;
}
like image 9
Kareem Avatar answered Nov 07 '22 18:11

Kareem


Another way to do it is to serialize() both of the arrays and compare the strings.

http://php.net/manual/en/function.serialize.php

like image 13
user151841 Avatar answered Nov 07 '22 18:11

user151841