0
0
PhpHow-ToBeginner · 3 min read

How to Use array_diff in PHP: Syntax and Examples

The array_diff function in PHP compares two or more arrays and returns an array containing values from the first array that are not present in any of the other arrays. It is useful to find unique elements by comparing arrays easily.
📐

Syntax

The array_diff function compares the values of the first array against one or more other arrays and returns the values in the first array that are not present in any of the others.

  • array_diff(array $array, array ...$arrays): array
  • $array: The main array to compare from.
  • $arrays: One or more arrays to compare against.
php
array_diff(array $array, array ...$arrays): array
💻

Example

This example shows how array_diff returns values from the first array that are not in the second array.

php
<?php
$array1 = ["apple", "banana", "cherry", "date"];
$array2 = ["banana", "date", "fig"];

$result = array_diff($array1, $array2);
print_r($result);
?>
Output
Array ( [0] => apple [2] => cherry )
⚠️

Common Pitfalls

1. array_diff compares values only, not keys. So keys from the first array are preserved but not compared.
2. It uses loose comparison, so types matter (e.g., string "1" and integer 1 are considered equal).
3. Passing non-array arguments causes errors.
4. The returned array keeps original keys, which may be non-sequential.

Example of a common mistake and fix:

php
<?php
// Wrong: expecting keys to be compared
$array1 = ["a" => "apple", "b" => "banana"];
$array2 = ["a" => "apple"];
$result = array_diff($array1, $array2);
print_r($result); // 'banana' remains because values differ

// Right: keys are not compared, only values
// Use array_diff_key to compare keys instead
$result_keys = array_diff_key($array1, $array2);
print_r($result_keys);
?>
Output
Array ( [b] => banana ) Array ( )
📊

Quick Reference

FunctionDescription
array_diff($array1, $array2)Returns values in $array1 not in $array2
array_diff_key($array1, $array2)Returns keys in $array1 not in $array2
array_intersect($array1, $array2)Returns values common to both arrays
array_diff_assoc($array1, $array2)Returns key-value pairs in $array1 not in $array2

Key Takeaways

Use array_diff to find values in the first array that are missing from others.
array_diff compares values only, not keys, and preserves original keys in the result.
Pass only arrays to array_diff to avoid errors.
For key comparison, use array_diff_key instead.
Returned arrays may have non-sequential keys; reindex if needed.