PHP

Find Differences Between Two PHP Associative Arrays

Discover how to use `array_diff_assoc()` in PHP to find entries that are present in the first array but not in the second, based on both key and value.

<?php

$array1 = [
    "a" => "apple",
    "b" => "banana",
    "c" => "cherry",
    "d" => "date"
];

$array2 = [
    "a" => "apple",
    "c" => "grape", // Different value for key 'c'
    "e" => "elderberry"
];

// Find elements in $array1 that are not in $array2 (based on both key and value)
$differences = array_diff_assoc($array1, $array2);

echo "Elements in \$array1 not matching in \$array2 (key and value):
";
print_r($differences);

$array3 = [
    "name" => "Alice",
    "age" => 30,
    "city" => "New York"
];

$array4 = [
    "name" => "Alice",
    "age" => 30,
    "city" => "London", // Different city
    "occupation" => "Engineer"
];

$userDifferences = array_diff_assoc($array3, $array4);
echo "User profile differences (from array3):
";
print_r($userDifferences);

?>
How it works: The `array_diff_assoc()` function compares two (or more) associative arrays and returns a new array containing all entries from the first array that are not present in any of the other arrays, considering both the key and the value. This is useful for identifying specific changes or unique entries between datasets where both identifiers and their associated values matter.

Need help integrating this into your project?

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

Hire DigitalCodeLabs