← Back to all snippets
PHP

Find Common Elements Between Two PHP Arrays

Efficiently find common values or key-value pairs between two PHP arrays using `array_intersect()` and `array_intersect_assoc()` functions.

$array1 = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow'];
$array2 = ['e' => 'red', 'f' => 'green', 'g' => 'purple'];
$array3 = ['a' => 'red', 'b' => 'green', 'c' => 'orange'];

// Find common values (values must be identical)
$commonValues = array_intersect($array1, $array2);
print_r("Common Values (array_intersect):
");
print_r($commonValues);

// Find common key-value pairs (keys and values must be identical)
$commonKeyValuePairs = array_intersect_assoc($array1, $array3);
print_r("
Common Key-Value Pairs (array_intersect_assoc):
");
print_r($commonKeyValuePairs);
How it works: This snippet illustrates how to find the common elements between two or more arrays using PHP's built-in `array_intersect()` and `array_intersect_assoc()` functions. `array_intersect()` returns an array containing all values that are present in all the input arrays. `array_intersect_assoc()` does the same but also checks for matching keys. These functions are crucial for comparing and filtering arrays based on their shared content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs