In this tutorial we will learn How To Remove Common Values from two Arrays with PHP, We can use PHP array_diff() function, array_merge() function and array_unique() function to remove the values that are common in both arrays, new array will only have unique values.
Table of Contents
PHP array_diff() function
PHP array_diff() function compares two or more arrays and return the array with difference of those arrays.
PHP array_diff() function removes all values of first array that are present in other arrays and return an array with values that are present in first array but they are not present in other arrays.
PHP array_merge() function
PHP array_merge() function merges or combines two or more arrays.
If two values have same keys then PHP array_merge() function will replace former values with the last one.
PHP array_unique() function
PHP array_unique() function removes duplicate values from the array.
If two values are same then first value is kept with it's key while second one is removed.
Look at the following code in which we have used three different functions step wise 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");
$arrayDifference1 = array_diff($array1,$array2);
$arrayDifference2 = array_diff($array2,$array1);
$result = array_merge($arrayDifference1,$arrayDifference2);
$result = array_unique($result);
print_r($result);
?>
Demo
The resulting array has no common values and it only contains unique values.
First, difference of two arrays is calculated twice with the help of array_diff() function, notice that each time order of arrays is changed.
Then these two resulting arrays are combined together using array_merge() function.
In the end array_unique() function is used to further remove the duplicate values from the combined array.