PHP

Find Common Elements Across Multiple PHP Arrays

Efficiently determine the intersection of an arbitrary number of PHP arrays, identifying values that are present in all given arrays.

<?php

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];
$array3 = [4, 5, 7, 8, 9];
$array4 = [5, 10, 11, 12];

$allArrays = [$array1, $array2, $array3, $array4];

// Use call_user_func_array with array_intersect to find common elements
$commonElements = call_user_func_array('array_intersect', $allArrays);

print_r($commonElements);
// Output: Array ( [0] => 5 )

// Example with associative arrays (using array_intersect_assoc for keys+values)
$assoc1 = ['a' => 1, 'b' => 2, 'c' => 3];
$assoc2 = ['b' => 2, 'c' => 4, 'd' => 5];
$assoc3 = ['b' => 2, 'e' => 6, 'f' => 7];

$allAssocArrays = [$assoc1, $assoc2, $assoc3];

$commonAssocElements = call_user_func_array('array_intersect_assoc', $allAssocArrays);
print_r($commonAssocElements);
// Output: Array ( [b] => 2 )

?>
How it works: This snippet demonstrates how to find the common elements (intersection) across an arbitrary number of PHP arrays. By using `call_user_func_array` with `array_intersect`, you can pass an array of arrays as arguments to `array_intersect`, which normally only takes two or more individual array arguments. The example also shows how to use `array_intersect_assoc` for associative arrays, which finds elements common in both key and value.

Need help integrating this into your project?

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

Hire DigitalCodeLabs