How to Get the DIfference Between Two Arrays in PHP

Last Updated on August 28, 2021 by Roshan Parihar

In this tutorial, learn how to get the difference between two arrays using PHP. The short answer is to use the array_diff() function and the two arrays in comma-separation.

You can also use other methods like array_diff_assoc() and array_diff_key() functions in PHP. Let’s find out how to use these functions to compare the two arrays and find the difference.

Method 1: Using array_diff() to Get Difference Between Two Arrays in PHP

To get the difference between two arrays, you have to use the array_diff() function. It requires the two arrays to pass as an argument of the function in comma-separation. The function compares the values of two arrays without considering the keys to return the difference. It prefers the first array to match with the second to give the result.

Output

Array ( [Ricksaw] => 4 )

The above contains different keys but with matching values. The function only compares the values to give the result of the difference between them. When the function compares the two arrays, it gets the last element whose value is not present in the second array.

Method 2: Using array_diff_assoc() to Find the Difference Using PHP

When you want to compare the two arrays according to their keys and values, you have to use the array_diff_assoc() function of PHP. It takes two comma-separated array variables as its arguments to find the difference between the first array with the second array.

Output

Array ( [Bike] => 5 [Car] => 9 [Ricksaw] => 4 )

The above example gives the elements of the first array in the output whose keys and values are not present in the second array.

Method 3: Using array_diff_key() in PHP

In addition to the above methods, you can also use the array_diff_key() to get the variations between the arrays according to the keys. It takes two arguments in comma-separation to get the result of the comparison.

Output

Array ( [3] => Ricksaw )

The above example showing the indexed array which is a sequential key array. The function always gives the last elements in the output after comparing in PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.