PHP Program to Find Common Elements in Arrays
array_intersect($array1, $array2) to find common elements between two arrays; it returns an array of values present in both.Examples
How to Think About It
Algorithm
Code
<?php $array1 = [1, 2, 3, 4]; $array2 = [3, 4, 5, 6]; $common = array_intersect($array1, $array2); print_r($common); ?>
Dry Run
Let's trace the example arrays [1, 2, 3, 4] and [3, 4, 5, 6] through the code.
Input arrays
$array1 = [1, 2, 3, 4], $array2 = [3, 4, 5, 6]
Find common elements
array_intersect compares elements and finds 3 and 4 in both arrays
Output result
Returns array with keys 2 => 3 and 3 => 4
| Step | Common Elements Found |
|---|---|
| Compare 1 | No |
| Compare 2 | No |
| Compare 3 | Yes (3) |
| Compare 4 | Yes (4) |
Why This Works
Step 1: Using array_intersect
The array_intersect function compares values of two arrays and returns those that appear in both.
Step 2: Preserves keys
It keeps the keys from the first array for the common elements, which helps identify their original positions.
Step 3: Simple and efficient
This built-in function is optimized and easy to use for finding common elements without manual loops.
Alternative Approaches
<?php $array1 = [1, 2, 3, 4]; $array2 = [3, 4, 5, 6]; $common = []; foreach ($array1 as $value) { if (in_array($value, $array2)) { $common[] = $value; } } print_r($common); ?>
<?php $array1 = [1, 2, 3, 4]; $array2 = [3, 4, 5, 6]; $common = array_filter($array1, fn($v) => in_array($v, $array2)); print_r($common); ?>
Complexity: O(n*m) time, O(min(n, m)) space
Time Complexity
The function compares each element of the first array with elements of the second, leading to O(n*m) in worst case where n and m are array sizes.
Space Complexity
It creates a new array for common elements, which at most is the size of the smaller array, so O(min(n, m)).
Which Approach is Fastest?
Using array_intersect is generally faster and more optimized than manual loops or array_filter for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| array_intersect | O(n*m) | O(min(n,m)) | Quick, built-in, optimized |
| Manual loop with in_array | O(n*m) | O(min(n,m)) | Learning and control |
| array_filter with in_array | O(n*m) | O(min(n,m)) | Functional style, concise code |
array_intersect for a quick and clean way to find common elements between arrays.array_intersect preserves keys from the first array, which can confuse output if not expected.