How to Compare Arrays Using array_diff in PHP

This article explains how to use the PHP array_diff() function to compare multiple arrays. You will learn the fundamental syntax of the function, how it evaluates and identifies differences based on values, and see practical code examples demonstrating its behavior.

Understanding the array_diff() Function

The array_diff() function in PHP compares the values of two or more arrays and returns the differences. Specifically, it compares the first array against one or more other arrays and returns an array containing all the entries from the first array that are not present in any of the subsequent arrays.

Syntax

array_diff(array $array1, array $array2, array ...$arrays): array

The function returns an array containing all the values of $array1 that do not exist in any of the other input arrays. Note that the original keys from $array1 are preserved in the returned array.


Basic Example: Comparing Two Arrays

In this example, we compare two arrays of colors. The function will identify which colors exist in the first array but are missing from the second array.

$array1 = ["red", "green", "blue", "yellow"];
$array2 = ["red", "green", "purple"];

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

print_r($result);

Output:

Array
(
    [2] => blue
    [3] => yellow
)

In this output, “blue” and “yellow” are returned because they exist in $array1 but not in $array2. The keys 2 and 3 from the original array are preserved.


Example: Comparing Multiple Arrays

You can pass multiple arrays to array_diff(). The function will exclude any values from the first array that appear in any of the other passed arrays.

$array1 = ["apple", "banana", "cherry", "orange"];
$array2 = ["banana"];
$array3 = ["orange", "melon"];

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

print_r($result);

Output:

Array
(
    [0] => apple
    [2] => cherry
)

Crucial Behaviors of array_diff()

To use array_diff() effectively, keep these three rules in mind:

  1. Value-Only Comparison: The function only compares the values of the arrays. The keys are completely ignored during the comparison process, though the keys of the first array are preserved in the final output.
  2. Case Sensitivity: The comparison is case-sensitive. For example, “Red” and “red” are treated as different values.
  3. String Conversion: Elements are compared as strings. This means that an integer 1 and a string '1' are considered equal during the comparison.