Remove Common Values from two Arrays PHP

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.

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.

$arrayDifference1 = array_diff($array1,$array2);
$arrayDifference2 = array_diff($array2,$array1);
$result = array_merge($arrayDifference1,$arrayDifference2);
$result = array_unique($result);


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.

How To Remove Empty Array Elements with PHP How To Remove Common Values from two Arrays with PHP How To Find sum of array values with PHP How To Shuffle array Values in PHP How to Remove Duplicate Values from an array with PHP PHP Sort Associative array by Key PHP Sort Associative array by Value Sort array in numerical order with PHP Sort array in alphabetical order with PHP Sort array in descending order PHP Sort array in ascending order in PHP How to merge two or more arrays in PHP Add elements to the end of an array in PHP Add elements to the start of an array in PHP PHP Remove First Element from an Array PHP Remove Last Element from an Array Check if Key Exists in array PHP Check if Value exists in array PHP How to reverse an array in PHP PHP Print array line by line PHP Echo array values using foreach loop Count array values in PHP PHP Count How Many Times Word appears in String How to Reverse a String with PHP Check if Variable is Null in PHP