PHP array_diff_key() Function

Last Updated on August 10, 2021 by Roshan Parihar

PHP array_diff_key() Function is used to compare the keys of two or more arrays. It returns the difference in the output after comparing. However, it will not compare the values of the arrays to get the result.

It compares the first array (array1) with the second array (array2) and other arrays in PHP. After that, it returns the keys in array1 that are not present in array2 and other arrays without considering the values.

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

Syntax of PHP array_diff_key() Function

array_diff_key(array1, array2, array3, …arrayN)

The array_diff_key() function takes comma-separated arrays as an argument to compare the difference among them.

Description of Parameters

Name Description
array1 Required. It is the first array to compare with the others.
array2 Required. It is the second array to compare against.
array3…arrayN optional. Specify more arrays to compare against.

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

Examples of PHP array_diff_key() Function

See the different examples to learn comparing the arrays keys using the array_diff_key() Function in PHP.

Example 1: Compare the Difference of Two Arrays in PHP

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

Output

Array ( [Car] => 9 )

The output shows that the key ‘Car’ of the first array is not present in the second array. That’s why it returns that key and prints in the output.

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

You can also compare more than two arrays according to their keys using the PHP array_diff_key() function. It returns the difference of the keys of the first array with the other arrays without comparing values.

Output

Array ( [WagonR] => 7 )

The above example shows that all the other array does not contain the key ‘WagonR’.

Example 3: Compare the Keys of Two Indexed Arrays in PHP

In addition to the above examples, you can also compare the keys of the indexed array in PHP. However, it will not consider the values to compare and find the difference. It is a sequence array and that’s why it gives the rest of the keys that are not present in other arrays.

Output

Array ( [3] => Ricksaw )

The above example shows that that the other arrays do not have to fourth key. It prints the values of the key that is not present in the other arrays 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.