如何检查$courseAreas
数组至少包含 " ayrshire"
和" fife"?
我已经尝试了以下代码,但它不起作用:
$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = (count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) >= 2 ? true : false);
答案 0 :(得分:2)
尝试将? true : false
放在大括号外
$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = (count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) >= 2) ? true : false;
var_dump($includesAyrshireAndFife);
$courseAreas = array('ayrshire', 'stirlingshire', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = (count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) >= 2) ? true : false;
var_dump($includesAyrshireAndFife);
但是你的原作似乎也能很好地工作......在什么情况下你会发现它失败了?
答案 1 :(得分:1)
$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) > 1;
你甚至不需要tenary运营商因为>它已经是布尔表达式。
修改:
我注意到你的代码也有效。我只是缩短它。
答案 2 :(得分:0)
您可以使用in_array()