Shehzad Bilal
Shehzad Bilal

Reputation: 2523

Search if any element of array found in another array in PHP

How can I search an element of an array in another array? If any element is found, the search function returns true, else it returns false.

For example:

$mainArray = array(1,2,3,4,5);
$tosearch = array(2,7); //returns true as 2 is in main array.
$tosearch = array(7,8); //return false as no element found in main array.  

Upvotes: 2

Views: 1723

Answers (3)

user895378
user895378

Reputation:

var_dump((bool) array_intersect($arr1, $arr2));

EDIT

Just to clarify my answer ... since you are looking for TRUE or FALSE, I include a boolean typecast (bool). Without the cast, array_intersect will return a truthy array, but still an array.

Upvotes: 4

Ben D
Ben D

Reputation: 14479

Are you sure you're working in PHP, or is your array syntax just for illustration?

In any case, look at the array_intersect() function:

http://php.net/manual/en/function.array-intersect.php

Upvotes: 0

rabusmar
rabusmar

Reputation: 4143

You can use array_intersect for that, like this:

if (array_intersect($mainArray, $tosearch)) {
    // elements in common
}

Upvotes: 2

Related Questions