PHP array_diff_assoc function

The PHP function array_diff_assoc is used to compare two or more arrays and return the differences between them based on their keys. This function is particularly useful when comparing associative arrays, which have keys that are associated with values.

How it Works

The array_diff_assoc function compares the keys of the arrays passed to it and returns the values of the first array that are not present in the second or any other arrays. In other words, it returns an array that contains the differences between the arrays based on the keys.

For example, consider the following two arrays:

$array1 = array("a" => "apple", "b" => "banana", "c" => "cherry");
$array2 = array("a" => "apple", "c" => "cherry", "d" => "date");

When we compare these two arrays using array_diff_assoc, we get the following result:


$array1 = array("a" => "apple", "b" => "banana", "c" => "cherry");
$array2 = array("a" => "apple", "c" => "cherry", "d" => "date");

$result = array_diff_assoc($array1, $array2);

    [b] => banana

As we can see, the array_diff_assoc function has returned the value banana which is associated with the key b in $array1, but not in $array2.

Benefits of Using array_diff_assoc

  • Accurate comparison of arrays based on keys: By comparing the keys of the arrays, array_diff_assoc ensures that the comparison is accurate and only returns values that are truly different.

  • Efficient comparison: array_diff_assoc is faster and more efficient than other methods of comparing arrays, such as looping through the arrays and comparing each element manually.

  • Easy to use: The array_diff_assoc function is easy to use and requires only a few lines of code to compare arrays.


In conclusion, the PHP array_diff_assoc function is a useful tool for comparing arrays and finding the differences between them based on their keys. Whether you are working with associative arrays or just want to ensure that your array comparisons are accurate, array_diff_assoc is a great choice.

Practice Your Knowledge

What does the array_diff_assoc() function in PHP do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?