Get common elements from two different arrays in PHP
Suppose we have two PHP array and each of them contains some elements. Now we want to get common elements or values from those two arrays with PHP. Then how we can do it?
Well, this article is actually focusing on how to find common elements from two different arrays. Our task is to find and show those elements that is available in both of the two arrays.
So keep reading to get the solution…
PHP has an inbuilt function that can help us to perform this task. I am talking about the array_intersect() function. This function can compare the values from two arrays and then return the matches available. We just need to pass the arrays as the argument to this PHP function and the function will return the common elements.
Now it is the time to see the example PHP code:
<?php $arr1 = array("Tree", "Grass", "Bird", "Water", "Cloud", "Sun"); $arr2 = array("Moon", "Star", "Cloud", "Butterfly", "Bird"); $arr_common= array_intersect($arr1, $arr2); print_r($arr_common); ?>
As you can see in the above code, we have taken two arrays and each of them has some string values. Then we pass them to the array_intersect() function and finally print the result.
We will get and show the common elements between those arrays. The code we have written is for doing this specific task.
Now, its time to check if it is working or not. If we run the above PHP code, it will show the result as you can see below:
Array (  => Bird  => Cloud )
From the result, you can see that each of the elements of the newly formed array exists in both of the two arrays we passed as arguments to the array_intersect() function. So from the result, it is clear that we have successfully able to find common elements from the two different arrays.