PHP array_diff_assoc() Function

Last Updated on August 10, 2021 by Roshan Parihar

PHP array_diff_assoc() Function is used to get the difference between two or more arrays in PHP. It first compares the keys and values of the two arrays to return the difference between them. After that, it returns the keys and values in array1 that are not present in array2 and other arrays.

Let’s find out the use of the array_diff_assoc() function with the examples given below.

Syntax of PHP array_diff_assoc() Function

array_diff_assoc(array1, array2, array3, …arrayN)

The array_diff_assoc() function takes any number of comma-separated arrays as an argument to compare and find the difference among them. After that, it returns the difference in the output.

Description of Parameters

Name Description
array1 Required. It is the first array of the function.
array2 Required. It is the second array to compare with the first array.
array3…arrayN optional. Compare more arrays to compare with the first and second arrays in PHP.

Let’s find out the use of the PHP array_diff_assoc() Function with the example given below.

Examples of PHP array_diff_assoc() Function

See the different examples to learn comparing the array keys and values using the array_diff_assoc() Function in PHP.

Example 1: Get the Difference of Two Arrays in PHP

Suppose that, you have two arrays that you want to use to get the difference between them according to keys and values. The PHP array_diff_assoc() Function compares the keys and values of the first array with the second array. After that, it returns the difference of keys and values of the first array that are not present in the second array.

Output

Array ( [Ricksaw] => 4 )

The output in the above example shows that there is only one array element that shows keys and values are not present in the second array.

Example 2: Compare the Difference Among More than Two Arrays in PHP

You can also compare the difference for more than two arrays using the PHP array_diff_assoc() function.

Output

Array ( [Ricksaw] => 4 )

Example 3: What if the keys are the same but values are different?

If the keys are the same and values are different for two arrays, the function gives preference to the elements of the first array to print in the output. When the function gets all the elements of the first array are not matching with the elements of the second array, it prints all the elements of the first array in the output.

Output

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

the above example shows that all the elements of first array are not matching with all the elements of second array 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.