Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array_intersect as boolean

Tags:

php

I have two arrays and I need to check if they have values in common and the return value must be a boolean. Can I use array_intersect() like this or there is a better way?

$result = (bool) array_intersect($array1, $array2);

Thank you.

like image 247
user3477054 Avatar asked Oct 18 '25 16:10

user3477054


2 Answers

Just check the content of array_intersect($array1, $array2)

$result = count(array_intersect($array1, $array2)) > 0;
like image 82
Cid Avatar answered Oct 20 '25 05:10

Cid


Yes, your code will work fine. When casting to a boolean, an empty array is considered false, while an array with any elements in it (i.e. one for which count($array) > 0) will be considered as true. From the manual:

When converting to boolean, the following values are considered FALSE:
...
- an array with zero elements
...
Every other value is considered TRUE (including any resource and NAN).

like image 27
Nick Avatar answered Oct 20 '25 05:10

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!