This tutorial will discuss about unique ways to check if an array contains any value from another array in php.
Table Of Contents
Method 1: Using array_intersect() function
Suppose we have two arrays, and we want to check if the second array contains any value from the first array or vice versa.
For that, we can fetch the common values between two arrays. Pass both the arrays into the array_intersect()
function and it will return a new array containing only the common values from both the arrays.
Then we can check the size of this new array. If it is not empty, then it means first array has at least a value from the second array.
Let’s see the complete example,
<?php $arr1 = array(23, 89, 16, 11, 21, 18, 90); $arr2 = array(12, 14, 6, 18, 10, 8, 9); // Check if two arrays have any common value $commonValues = array_intersect($arr1, $arr2); if (!empty($commonValues)) { echo "Yes, first array has atleast a value from the second array"; } else { echo "No, first array does not have any value from the second array"; } ?>
Output
Frequently Asked:
- Check if value exists in associative array in PHP
- Check if a value exists in multidimensional array in PHP
- Check if all elements in Array are true in PHP
- Check if all elements in Array are equal in PHP
Yes, first array has atleast a value from the second array
Method 2: Using foreach()
To check if an array contains a value from the second array, we can iterate over all the elements of first array using foreach()
function. During iteration, for each value check if it exist in the second array or not using the in_array()
function.
For this, we will pass this value and the second array as arguments to the in_array()
function. If it returns true, then it means that the value exists in the second area. As soon as we find a value from the first array that exist in the second array we will mark our result as true and break the loop. At the end of for loop we can check if our result value is true that means first array has at least a value from the secondary array.
Let’s see the complete example,
<?php $arr1 = array(23, 89, 16, 11, 21, 18, 90); $arr2 = array(12, 14, 6, 18, 10, 8, 9); $result = false; // Iterate over all elements of first array foreach ($arr1 as $value) { // Check the ith value from first array // exists in second array if (in_array($value, $arr2)) { // If match is found, break the loop $result = true; break; } } if ($result) { echo "Yes, first array has atleast a value from the second array"; } else { echo "No, first array does not have any value from the second array"; } ?>
Output
Yes, first array has atleast a value from the second array
Summary
We learned about two ways to check if an array contain any value from another array in PHP.