Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - how to check if at least one element of first array exists in second array

Tags:

I have two arrays : array("blue", "yellow") and array("blue", "green", "red", "purple"). Is there a function that will check if those two arrays have at least one element value in common ("blue") - just return true or false.

like image 661
Tamik Soziev Avatar asked May 21 '12 20:05

Tamik Soziev


People also ask

How do you check if an element in one array is in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you check if an array exists in another array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do I check if two arrays have common elements in PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.


1 Answers

$array1 = array("blue", "yellow");
$array2 = array("blue", "green", "red");

return count(array_intersect($array1, $array2)) > 0;
like image 177
Travesty3 Avatar answered Oct 07 '22 18:10

Travesty3