PHP

Find Common Elements with Matching Keys and Values in Two Arrays

Learn to identify elements that exist in both arrays, ensuring that both their keys and their associated values are identical using `array_intersect_assoc`.

<?php

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

$array2 = [
    'a' => 'apple',
    'b' => 'grape',
    'c' => 'cherry',
    'e' => 'elderberry'
];

$commonElements = array_intersect_assoc($array1, $array2);

print_r($commonElements);

// Expected output: Array ( [a] => apple [c] => cherry )

?>
How it works: The `array_intersect_assoc()` function returns an array containing all elements from `array1` that are present in `array2`, but only if both the key and the value match. This is stricter than `array_intersect()` which only compares values, and useful when the associative keys are also important for comparison.

Need help integrating this into your project?

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

Hire DigitalCodeLabs