PHP

Find Differences Between Associative Arrays (Key-Value Pairs)

Compare two associative PHP arrays to identify entries that are present in the first but not in the second, considering both keys and their corresponding values.

<?php
$array1 = [
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    'd' => 'date'
];

$array2 = [
    'a' => 'apple',
    'b' => 'grape', // Value differs from array1
    'e' => 'elderberry' // New key not in array1
];

// Finds entries in array1 that are not present in array2 
// (both key and value must match for elements to be considered equal)
$diff = array_diff_assoc($array1, $array2);
/*
$diff will be:
[
    'b' => 'banana', // Because 'b' in array1 has 'banana', but in array2 has 'grape'
    'c' => 'cherry', // Because 'c' is not present in array2
    'd' => 'date'    // Because 'd' is not present in array2
]
*/

// If you only care about keys present in array1 but not array2
$diffKeys = array_diff_key($array1, $array2);
/*
$diffKeys will be:
[
    'c' => 'cherry',
    'd' => 'date'
]
*/
?>
How it works: The `array_diff_assoc()` function compares two or more arrays and returns all entries from the first array that are not present in any of the other arrays, considering both the keys and their corresponding values. If you only need to compare based on keys, `array_diff_key()` provides a similar functionality, returning elements whose keys exist in the first array but not in the others.

Need help integrating this into your project?

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

Hire DigitalCodeLabs