In PHP's daily development, the array_diff() function is often used to perform differential operations on arrays. It can help us find values that exist in one array but not in other arrays. This is very practical in handling scenarios such as data filtering and permission control.
However, a often overlooked question is: Will array_diff() retain the key name of the original array when returning the result? Or will it automatically reindex the array?
Let’s take a look at a simple example:
<?php
$array1 = ["a" => "green", "b" => "brown", "c" => "blue", "red"];
$array2 = ["green", "yellow", "red"];
$result = array_diff($array1, $array2);
print_r($result);
?>
The output result is:
Array
(
[b] => brown
[c] => blue
)
As you can see, the result returned by array_diff() retains the key name of the original array $array1 . Even the string key is not reindexed.
If you really want to re-index the result array, you can use array_values() manually:
$reindexed = array_values(array_diff($array1, $array2));
print_r($reindexed);
Output:
Array
(
[0] => brown
[1] => blue
)
In this case, the key name is reset to a continuous number index starting from 0 .
Suppose the user submits a set of tags and you want to remove the content that already exists in the system default tag:
<?php
$userTags = [
10 => "php",
11 => "html",
12 => "custom"
];
$defaultTags = ["php", "html", "css", "javascript"];
$finalTags = array_diff($userTags, $defaultTags);
print_r($finalTags);
?>
Output result:
Array
(
[12] => custom
)
This shows that the function does retain the key names of the user's original array, which can be valuable information in database insertion or update operations.
array_diff() only compares values , regardless of key names.
If you want to compare based on key names, you can use array_diff_key() .
If you want to compare key names and values at the same time, you can use array_diff_assoc() .