PHP, From Two Array Remove Duplicate Values.

In this article, we'll go over some PHP code for removing duplicate values from two arrays. We may eliminate the values that are shared by both arrays by utilizing the PHP array_diff() function, the array_merge() function, and the array_unique() function. After this, the new array will only contain unique values.

PHP array_diff() function

PHP array_diff() function allows for comparing two or more arrays and the return of an array containing only the differences.


The PHP array_diff() function returns a new array containing only the elements present in the first array and absent from the other arrays.

PHP array_merge() function

The PHP array_merge() function combines two or more arrays into a single array. The array_merge() function will merge duplicate values with matching keys into a single value.

PHP array_unique() function

The array_unique() function in PHP eliminates duplicate values in an array.


In the array where two values are identical, the first value is kept along with its associated key, while the second value is removed.


Look at the following piece of code, in which we have shown three distinct functions step-by-step to remove all common values in two arrays.


<?php
$array1=array("a"=>"HTML","b"=>"CSS","c"=>"CSS","d"=>"JavaScript");
$array2=array("e"=>"CSS","f"=>"JavaScript","g"=>"PHP","h"=>"jQuery");
$diff1 = array_diff($array1,$array2);
$diff2 = array_diff($array2,$array1);
$result = array_merge($diff1,$diff2);
$result = array_unique($result);
print_r($result);
?>


Output

Array ( [a] => HTML [g] => PHP [h] => jQuery )


There are no duplicates in the final array, which consists entirely of one-of-a-kind data.


The array_diff() function is used to compute the difference between two arrays twice. It is important to note that the order of the arrays is flipped between each calculation.


Afterwards, the arrays generated by these two functions are merged using the array_merge() function.


In the final step, the array_unique() function is called upon to eliminate any remaining instances of duplicate data from the combined array.