dongwu8653 2019-04-16 16:41
浏览 31
已采纳

数组减少变量中的返回布尔值

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?

  • 写回答

3条回答 默认 最新

  • dongtang6775 2019-04-16 16:52
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?