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.
Just check the content of array_intersect($array1, $array2)
$result = count(array_intersect($array1, $array2)) > 0;
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With