Current Location: Home> Latest Articles> Notes when using array_diff()

Notes when using array_diff()

M66 2025-06-06

In PHP, array_diff() is a very common function that can find the differences between arrays. But when we use it to process associative arrays in actual projects, if we do not understand how it works, we may fall into many "pits".

This article will explain in-depth the behavior of array_diff() , common misunderstandings, and some practical techniques in associative array processing.

1. Basic usage of array_diff()

 $array1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$array2 = ['a' => 'apple', 'b' => 'blueberry'];

$result = array_diff($array1, $array2);
print_r($result);

Output:

 Array
(
    [b] => banana
    [c] => cherry
)

Explanation: array_diff() only compares "value" and ignores the key name . In this example, although the keys of $array1['b'] = 'banana' are the same as $array2['b'] = 'blueberry' , 'banana' is considered one of the differences due to the different values.

2. Common misunderstandings and pitfalls

1. Ignore the comparison of key names

Misconception: Many developers think array_diff() will compare key-value pairs.

 $a = ['id' => 1, 'name' => 'John'];
$b = ['name' => 'John', 'id' => 2];

var_dump(array_diff($a, $b));

Output:

 array(1) {
  ["id"]=>
  int(1)
}

Although 'name' => 'John' is the same in both arrays, because array_diff() does not look at the key, it only focuses on whether the value exists. So 'id' => 1 is considered different because 1 is not in the value of $b .

? Solution: If you want to compare keys and values ​​at the same time, it is recommended to use array_diff_assoc() :

 array_diff_assoc($a, $b);

It will compare keys and values ​​at the same time, avoiding this "illusion".

2. Ignore the comparison of data types

 $a = ['value1' => 123];
$b = ['value2' => '123'];

print_r(array_diff($a, $b));

Output:

 Array
(
)

Pit point: array_diff() uses a strict comparison of right or wrong ( == ), so 123 and '123' are considered the same.

? Tip: If you need strict comparison (the values ​​and types must be consistent), you can use array_diff() 's variant array_diff_uassoc() with a custom comparison function.

 $result = array_udiff($a, $b, function($a, $b) {
    return $a === $b ? 0 : ($a > $b ? 1 : -1);
});

3. Error expectations when dealing with multidimensional arrays

array_diff() is a one-dimensional array tool , and for multi-dimensional arrays it does not compare recursively.

 $a = ['info' => ['id' => 1, 'name' => 'Tom']];
$b = ['info' => ['id' => 1, 'name' => 'Tom']];

print_r(array_diff($a, $b));

Output:

 Array
(
    [info] => Array
        (
            [id] => 1
            [name] => Tom
        )
)

Cause: The value of the array type is treated as a string in array_diff() , and it cannot directly compare whether the contents of the two arrays are equal.

? Solution: If you want to compare multi-dimensional arrays, you need to write recursive functions manually, or compare them with serialization conversion:

 $a_serialized = array_map('serialize', $a);
$b_serialized = array_map('serialize', $b);

$diff = array_diff($a_serialized, $b_serialized);

3. Practical skills and application scenarios

Scenario 1: Determine whether the database data has been modified

Suppose you pull a piece of data from the database to $original , the user submits a form to $new_data , and you want to know which fields have changed:

 $original = ['name' => 'Alice', 'email' => 'a@m66.net'];
$new_data = ['name' => 'Alice', 'email' => 'alice@m66.net'];

$changed = array_diff_assoc($new_data, $original);

This way you can accurately obtain which fields have been changed by the user.

Scenario 2: Comparison of the differences between two configuration files

You have two configuration arrays $config1 and $config2 :

 $config1 = include 'http://m66.net/config/old.php';
$config2 = include 'http://m66.net/config/new.php';

$diff = array_diff_assoc($config2, $config1);

This allows easy access to configuration changes, especially suitable for writing in automated scripts.

Summarize

method Compare content Whether to distinguish between types Suitable for scenes
array_diff() Compare values ​​only no Simple value comparison
array_diff_assoc() Compare value + key name no Form, configuration comparison
array_udiff() Custom comparison method Customizable Strict type comparison
serialize + array_diff() Multidimensional array comparison No (scalable) Multidimensional structure comparison

When using array_diff() , be clear about what you are comparing. Don't be misled by key names, and don't forget the impact of the type. Only by understanding these principles can you truly use this tool function.

If you encounter special comparison needs in your project, please write a gadget function encapsulation logic by hand - this not only improves the readability of the code, but also reduces the probability of breaking into a pit.