Search code examples
phparraysmultidimensional-arrayarray-difference

Array comparision in php to get only difference


Following Below are two arrays which i wanna compare and remove the same values something like array_diff() Function and i want to store the result in third array

$array1 = Array([0] => Array([a] => XYZ,[b] => ABC))
$array2 = Array([0] => Array([a] => XYZ,[b] => ABC),[1] => Array([a] => PQR,[b] => XYZ))
$array3 = array_diff($array1,$array2);
//$array3 value must return this value Array([1] => Array[a]=> PQR,[b] => XYZ)

I don't know what i am doing wrong but i am getting error that array cannot be converted into string. Can anyone help me with this? Thanks in advance


Solution

  • If you are sure that your $array2 will always contain more elements than $array1 then here is your solution:

    $array1 = array(array('a' => 'XYZ','b' => 'ABC'));
    $array2 = array(array('a' => 'XYZ','b' => 'ABC'),array('a' => 'PQR','b' => 'XYZ'));
    $limit = count($array2);
    $array3 = array();
    for($i=0;$i<$limit;$i++){
      if(empty($array1[$i]))
        $array3[] = $array2[$i];
    
      $array3[] = array_diff($array1[$i],$array2[$i]);
    }
    foreach($array3 as $k=>$a3){
      if(empty($a3)||($a3===NULL))
        continue;
      $result[$k] = $a3;
    }
    var_dump($result); //array(1) { [1]=> array(2) { ["a"]=> string(3) "PQR" ["b"]=> string(3) "XYZ" } }
    

    Please note that array_diff works on 1D array and you was providing 2D arrays as parameter and that's why it wasn't working.

    Also your way of defining $array1 and $array2 is wrong, please check this solution for right syntax.

    I hope it helps