2

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.  

3 Answers 3

4
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.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use array_intersect for that, like this:

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

1 Comment

Thanks,, it work,, i didnt know that PHP got a builtin function for that.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.