PHP

Find Differences Between Two PHP Arrays

Discover how to compare two arrays to find differences in values or key-value pairs using PHP's `array_diff()` and `array_diff_assoc()` functions.

$array1 = ['apple', 'banana', 'orange', 'mango'];
$array2 = ['banana', 'grape', 'apple'];

// Find values in $array1 that are not in $array2
$diffValues = array_diff($array1, $array2);
echo "Values in array1 but not in array2:
";
print_r($diffValues);

$assocArray1 = [
    'a' => 'red',
    'b' => 'green',
    'c' => 'blue'
];
$assocArray2 = [
    'a' => 'red',
    'b' => 'yellow',
    'd' => 'purple'
];

// Find key-value pairs in $assocArray1 that are not in $assocArray2
// (key and value must match for elements to be considered the same)
$diffAssoc = array_diff_assoc($assocArray1, $assocArray2);
echo "
Key-value pairs in assocArray1 but not in assocArray2:
";
print_r($diffAssoc);
How it works: The `array_diff()` function compares the values of two (or more) arrays and returns a new array containing all values from the first array that are not present in any of the other arrays. `array_diff_assoc()` does a similar comparison but also takes the keys into account, meaning an element is considered different if its value *or* its key does not match. These functions are essential for comparing datasets and identifying unique or changed entries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs