CopyPastehas never been so tasty!

Get arrays difference using array_diff_assoc in PHP

by anonymous

  • 0
  • 0
  • 0
77 views


http://codingvilla.com/get-arrays-difference-using-array-diff-assoc-php-single-article-686.aspx

 

Purpose:

The array_diff_assoc is used to compare two or more arrays. First array is the reference array, then other are compared arrays only one is required other no’s of arrays is optional. array_diff_assoc(reference array,array1,array2,…..).

Code:

1. <?php
2. $name1=array(0=>"Tahreem",1=>"Rizwan",2=>"Anwar");
3. $name2=array(0=>"Misbah",1=>"Anwar",2=>"Rizwan");
4. $name3=array(0=>"Anwar",1=>"Rizwan",2=>"Tahreem");
5. print_r(array_diff_assoc($name1,$name2,$name3));
6. ?>

Output:

Array ( [0] => Tahreem [2] => Anwar )

Explanation:

Both keys/index number and values are used in comparison. On line 2 $name1 is reference array on line 3 and line 4 are arrays that are to be compared with reference array. First the index [0] value is compared with other arrays if that index value is different on that index in other arrays so that will be the output. Then index [1] of reference array value is compared with other arrays if it is present in any other array on index [1] it will not be the output. Then index [2] value is compared with other array values if it is present any other array on index [2] it will not be printed otherwise output will be printed.

Add A Comment: