PHP
Find Common Key-Value Pairs in Associative Arrays
Discover how to efficiently find and extract elements that have identical keys and values across two PHP associative arrays using the built-in `array_intersect_assoc` function.
<?php
$array1 = [
'id' => 1,
'name' => 'Alice',
'age' => 30,
'city' => 'New York'
];
$array2 = [
'id' => 1,
'name' => 'Alice',
'age' => 25,
'country' => 'USA'
];
$common_elements = array_intersect_assoc($array1, $array2);
print_r($common_elements);
// Expected output:
// Array
// (
// [id] => 1
// [name] => Alice
// )
?>
How it works: This snippet demonstrates `array_intersect_assoc()`, a powerful PHP function for comparing two or more associative arrays. It returns a new array containing all elements that are present in all the input arrays, matching both by key and by value. This is particularly useful for identifying identical data entries or configurations across different data sources.