PHP

Comparing Two Arrays to Find Differences by Value, Key, or Both

Discover how to use PHP's array_diff, array_diff_assoc, and array_diff_key functions to identify unique elements or differences between two arrays based on values, keys, or both.

<?php

$array1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'date'];
$array2 = ['a' => 'apple', 'c' => 'cranberry', 'e' => 'elderberry'];

// Find values in array1 that are not in array2 (value-only comparison)
$diffValues = array_diff($array1, $array2);
echo "Differences by value (array1 vs array2):
";
print_r($diffValues);
/* Output:
Array
(
    [b] => banana
    [c] => cherry
    [d] => date
)
*/

echo "
";

// Find entries in array1 that are not in array2 (key AND value comparison)
$diffAssoc = array_diff_assoc($array1, $array2);
echo "Differences by key and value (array1 vs array2):
";
print_r($diffAssoc);
/* Output:
Array
(
    [b] => banana
    [c] => cherry
    [d] => date
)
*/

echo "
";

// Find keys in array1 that are not in array2 (key-only comparison)
$diffKeys = array_diff_key($array1, $array2);
echo "Differences by key (array1 vs array2):
";
print_r($diffKeys);
/* Output:
Array
(
    [b] => banana
    [d] => date
)
*/
How it works: This snippet illustrates how to compare two arrays and find their differences using various `array_diff` functions. `array_diff` compares only the values. `array_diff_assoc` compares both keys and values. `array_diff_key` compares only the keys. These functions are crucial for identifying elements unique to one array when comparing configuration sets, user permissions, or data updates.

Need help integrating this into your project?

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

Hire DigitalCodeLabs