Foreach loop with two arrays and if-condition evaluation to find matching values PHP?

In PHP, you can use nested foreach loops with if-conditions to find matching values between two arrays. This approach compares each element from the first array against all elements in the second array.

Problem Statement

Given two arrays, we need to find the common elements between them ?

$firstArray = array(10, 20, 30, 40, 50);
$secondArray = array(100, 80, 30, 40, 90);

Expected output should be ?

30
40

Using Nested Foreach Loops

The most straightforward approach uses nested foreach loops to compare each element ?

<?php
$firstArray = array(10, 20, 30, 40, 50);
$secondArray = array(100, 80, 30, 40, 90);

foreach($firstArray as $f) {
    foreach($secondArray as $s) {
        if($f == $s) {
            echo "The matching result is = " . $f . "<br>";
        }
    }
}
?>
The matching result is = 30
The matching result is = 40

Using Built-in Functions

PHP provides array_intersect() function for finding common elements more efficiently ?

<?php
$firstArray = array(10, 20, 30, 40, 50);
$secondArray = array(100, 80, 30, 40, 90);

$matchingValues = array_intersect($firstArray, $secondArray);

foreach($matchingValues as $value) {
    echo "The matching result is = " . $value . "<br>";
}
?>
The matching result is = 30
The matching result is = 40

Comparison

Method Performance Code Complexity
Nested foreach loops O(n×m) Higher
array_intersect() O(n+m) Lower

Conclusion

While nested foreach loops provide more control over the comparison logic, array_intersect() is more efficient and cleaner for simple matching operations. Use nested loops when you need custom comparison logic beyond equality.

Updated on: 2026-03-15T09:35:01+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements