PHP

Compare Two Associative Arrays to Find Differences by Key and Value

Discover how to identify elements that differ between two PHP associative arrays, considering both their keys and their corresponding values, using array_diff_assoc().

<?php

$array1 = [
    'id' => 1,
    'name' => 'Alice',
    'email' => '[email protected]',
    'status' => 'active'
];

$array2 = [
    'id' => 1,
    'name' => 'Bob',
    'email' => '[email protected]',
    'role' => 'admin'
];

// Find values in $array1 that are not in $array2 (comparing both key and value)
$differences1 = array_diff_assoc($array1, $array2);
print_r($differences1);

// Output:
// Array
// (
//     [name] => Alice
//     [email] => [email protected]
//     [status] => active
// )

// Find values in $array2 that are not in $array1 (comparing both key and value)
$differences2 = array_diff_assoc($array2, $array1);
print_r($differences2);

// Output:
// Array
// (
//     [name] => Bob
//     [email] => [email protected]
//     [role] => admin
// )

// Example with identical keys but different values:
$settings1 = ['theme' => 'dark', 'font_size' => 16];
$settings2 = ['theme' => 'light', 'font_size' => 16, 'sidebar' => 'left'];

$diffSettings = array_diff_assoc($settings1, $settings2);
print_r($diffSettings);

// Output:
// Array
// (
//     [theme] => dark
// )
How it works: The `array_diff_assoc()` function compares two (or more) associative arrays and returns an array containing all entries from the first array that are not present in any of the other arrays. Crucially, it considers both the key and the value for comparison. This is extremely useful for identifying exact discrepancies in configurations, user data, or any set of key-value pairs where both aspects must match for equality.

Need help integrating this into your project?

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

Hire DigitalCodeLabs