Compare multidimensional arrays in PHP Compare multidimensional arrays in PHP php php

Compare multidimensional arrays in PHP


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);  // truevar_dump($a === $b); // false
  2. With Triple equals ===, types matter:

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

Reference: Array operators


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

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


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;}