如何在变量中返回 bool 类型?我有代码:
$imageRes = array_reduce(['image', 'image1', 'image2'], function ($carry) {
return in_array($carry, ['image1', 'image2']);
});
我需要在 imageRes
中返回一个 bool 类型:true/false,如果 ['image1', 'image2']
中的元素之一code> 位于 ['image', 'image1', 'image2']
中。我该怎么做?
最佳答案
使用array_intersect()
计算其结果并将其转换为 bool 值,而不是 array_reduce()
。如果没有交集,count()
将为零,因此为 bool 值 false
。如果至少有一个值相交,count()
将大于 1,并且任何转换为 bool 值的非零数字都将为 true
。
$imageRes = (bool)count(array_intersect(['image1', 'image2'], ['image', 'image1', 'image2']));
输出:
bool(true)
关于php - 数组归约在变量中返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55712974/