Current Location: Home> Latest Articles> Will array_diff() retain the key name of the original array?

Will array_diff() retain the key name of the original array?

M66 2025-05-14

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?

1. Basic usage of array_diff()

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.

2. Compare with array_values()

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 .

3. Real scene application: filter the tags submitted by users

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.

4. Things to note

  • 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() .

5. Extended reading