How I can return boolean type in variable? I have code:
$imageRes = array_reduce(['image', 'image1', 'image2'], function ($carry) {
return in_array($carry, ['image1', 'image2']);
});
I need return
in imageRes
a boolean type: true/false, if one of the elements in ['image1', 'image2']
is in ['image', 'image1', 'image2']
. How I can do it?
Use array_intersect()
instead of array_reduce()
, count the result of that and cast it to a boolean. If there are no intersections, the count()
will be zero, thus a boolean false
. If there are at least one value intersecting, the count()
will be greater than one and any non-zero number cast to a boolean will be true
.
$imageRes = (bool)count(array_intersect(['image1', 'image2'], ['image', 'image1', 'image2']));
Output:
bool(true)
array_intersect()
If you just need to know if any of the elements are in both arrays use array_intersect()
, count the result and cast to boolean(!!
)
$ref_array = ['image1', 'image2'];
$array = ['image', 'image1', 'image2'];
$imageRes = !!count(array_intersect($array, $ref_array));
var_dump($imageRes);
A possible solution with array_reduce
would be like this:
$imageRes = array_reduce(
['image', 'image1', 'image2',],
function($carry, $item) {
return $carry || in_array($item, ['image1', 'image2']);
},
false //Initial value is false
);