PHP

Finding Array Differences (array_diff, array_diff_assoc)

Discover how to compare two or more PHP arrays to find differences in values or differences in both keys and values using array_diff() and array_diff_assoc().

<?php
$array1 = ['apple', 'banana', 'orange', 'color' => 'red'];
$array2 = ['banana', 'grape', 'apple', 'color' => 'blue'];
$array3 = ['orange', 'kiwi'];

// array_diff(): Compares values and returns values from array1 that are not present in array2 or array3
$diffValues = array_diff($array1, $array2, $array3);
// Result: ['color' => 'red']
echo "Differences in values (array_diff):
";
print_r($diffValues);

$array_numeric1 = [0 => 'a', 1 => 'b', 2 => 'c'];
$array_numeric2 = [0 => 'a', 1 => 'x', 3 => 'y'];
$diffNumericValues = array_diff($array_numeric1, $array_numeric2);
// Result: [1 => 'b', 2 => 'c']
echo "
Differences in values (numeric keys, array_diff):
";
print_r($diffNumericValues);

// array_diff_assoc(): Compares both keys and values
$diffKeysAndValues = array_diff_assoc($array1, $array2);
// Result: [0 => 'apple', 2 => 'orange', 'color' => 'red']
echo "
Differences in keys and values (array_diff_assoc):
";
print_r($diffKeysAndValues);
?>
How it works: `array_diff()` and `array_diff_assoc()` are powerful functions for identifying discrepancies between arrays. `array_diff()` returns all values from the first array that are not present in any other input array, performing a value-only comparison. `array_diff_assoc()` provides a stricter comparison, returning elements whose key-value pairs are not found in the other arrays. These functions are essential for tasks like detecting changes in data sets, comparing configurations, or validating user inputs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs