PHP
Finding the Difference Between Two Associative Arrays (Key-Value Wise)
Understand how to compare two associative arrays in PHP and find elements present in the first array but not in the second, based on both keys and values, using array_diff_assoc().
<?php
$array1 = [
'name' => 'Alice',
'age' => 30,
'city' => 'New York',
'occupation' => 'Engineer'
];
$array2 = [
'name' => 'Alice',
'age' => 30,
'city' => 'London', // Different value
'status' => 'active' // Key not in array1
];
$array3 = [
'name' => 'Bob', // Different value
'age' => 30,
'city' => 'New York'
];
// Difference between array1 and array2
$diff1_2 = array_diff_assoc($array1, $array2);
echo "Difference (array1 vs array2):
";
print_r($diff1_2);
// Difference between array1 and array3
$diff1_3 = array_diff_assoc($array1, $array3);
echo "
Difference (array1 vs array3):
";
print_r($diff1_3);
?>
How it works: The array_diff_assoc() function compares two (or more) associative arrays and returns all entries from the first array that are not present in any of the other arrays, based on *both* their keys and values. This is incredibly useful for detecting specific changes between two data sets, such as identifying updated fields in user profiles, tracking modifications to configurations, or identifying entries that have been removed between versions.