Current Location: Home> Latest Articles> How to print out the key names filtered out by array_diff_key()?

How to print out the key names filtered out by array_diff_key()?

M66 2025-06-06

How to print out the key names that are filtered out when using array_diff_key()?

In PHP, array_diff_key() is a very practical function that can be used to compare the key names of two arrays and return the key names that exist in the first array but not in the second array. In some scenarios, we not only need to obtain the filtered array, but also hope to obtain the filtered key names. This article will explain how to implement this function.

Use array_diff_key() function

The basic usage of the array_diff_key() function is as follows:

 $array1 = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4
];

$array2 = [
    'b' => 5,
    'd' => 6
];

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

print_r($result);

Output result:

 Array
(
    [a] => 1
    [c] => 3
)

As shown in the above example, array_diff_key() returns key-value pairs in $array1 that do not appear in $array2 . However, if we want to get the filtered key names, that is, those that exist in $array1 but do not appear in $array2 , we need to do some extra processing.

Get the filtered key name

In order to obtain the filtered key names, we can first use array_diff_key() to get the result, and then find the removed key names by comparing the key names of the two arrays.

 $array1 = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4
];

$array2 = [
    'b' => 5,
    'd' => 6
];

// Get the filtered array
$result = array_diff_key($array1, $array2);

// Get the filtered key name
$filteredKeys = array_keys($array1);
$remainingKeys = array_keys($result);
$removedKeys = array_diff($filteredKeys, $remainingKeys);

echo "Filtered key names: ";
print_r($removedKeys);

Output result:

 Filtered key names: Array
(
    [0] => a
    [1] => c
)

In this way, we can print out the key names that are filtered out when using array_diff_key() . The specific method is to first obtain all the key names in $array1 , and then use array_diff() to find out the key names that are not in $result , and finally obtain the filtered key names.

Summarize

Through the above example, we can see how to use array_diff_key() to compare key names of arrays and get filtered out key names. This operation is very common in PHP, especially when cleaning and comparing array data. If you want to retain the filtered key names, you can refer to the method in this article to achieve this.