PHP

Compare Two Arrays for Differences

Learn to identify differences between two PHP arrays using `array_diff`, `array_diff_assoc`, and `array_diff_key` to compare values, keys, or both.

$array1 = ['apple', 'banana', 'cherry', 'date'];
$array2 = ['banana', 'date', 'elderberry'];

// array_diff: Compares values and returns values from array1 that are not in array2
$diff_values = array_diff($array1, $array2);
print_r($diff_values); // Output: Array ( [0] => apple [2] => cherry )

echo "
";

$assoc1 = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow'];
$assoc2 = ['a' => 'red', 'e' => 'green', 'f' => 'blue'];

// array_diff_assoc: Compares both keys and values
$diff_assoc = array_diff_assoc($assoc1, $assoc2);
print_r($diff_assoc); // Output: Array ( [b] => green [c] => blue [d] => yellow )

echo "
";

// array_diff_key: Compares keys only
$diff_key = array_diff_key($assoc1, $assoc2);
print_r($diff_key); // Output: Array ( [b] => green [c] => blue [d] => yellow )

echo "
";

// Finding elements present in array2 but not array1 (reverse logic)
$missingInArray1 = array_diff($array2, $array1);
print_r($missingInArray1); // Output: Array ( [2] => elderberry )
How it works: This snippet explores PHP's array difference functions: `array_diff`, `array_diff_assoc`, and `array_diff_key`. `array_diff` finds values present in the first array but not in any subsequent arrays. `array_diff_assoc` is stricter, comparing both keys and values. `array_diff_key` only compares keys. These functions are incredibly useful for tasks like comparing two lists of items, detecting changes in configuration arrays, or identifying new/removed entries between two datasets.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs