OneBite.Dev - Coding blog in a bite size

Find The Common Elements In Two Arrays In PHP

Code snippet for how to Find The Common Elements In Two Arrays In PHP with sample and detail explanation

Finding common elements in two arrays in PHP can be a common requirement in web development. This brief article reveals an easy methodology to achieve this with a helpful code snippet.

Code Snippet

In PHP, we can use built-in functions array_intersect() to find common elements between two arrays. Here is a simple code snippet demonstrating it:

<?php
    $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
    $array2 = array("a" => "green", "yellow", "red");
    $result = array_intersect($array1, $array2);
    print_r($result);
?>

Code Explanation

In the above PHP script, we have two arrays $array1 and $array2. The array_intersect() function is used to compare the values of the two arrays. It returns the matches, i.e., common elements of both arrays.

Step-by-step breakdown of the above code:

  1. We start by declaring two arrays, $array1 and $array2.

  2. $array1 is an array with four elements, namely “green”, “brown”, “blue” and “red”.

  3. $array2 is another array containing three elements, which are “green”, “yellow”, and “red”.

  4. The array_intersect() function is called with $array1 and $array2 as arguments. This function compares the values of these two arrays.

  5. If a value from the first array is found in the second array, then the value is returned as part of the result.

  6. Ultimately, the $result variable will hold the common elements from both arrays.

  7. The print_r() function is then used to print the array $result. The output of this PHP script will be:

Array
(
    [a] => green
    [0] => red
)

It shows that the common elements in both arrays are “green” and “red”. That’s how you can easily find common elements in two arrays in PHP.

php