如何检查$courseAreas
数组是否至少包含"ayrshire"answers"fife"?
我尝试了以下代码,但它不起作用:
$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = (count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) >= 2 ? true : false);
尝试将? 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);
似乎工作
但你的原作似乎也很好。。。。你发现它在什么情况下会失败?
$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) > 1;
您甚至不需要tenary运算符,因为对于>,它已经是布尔表达式了。
编辑:
我注意到你的代码也能工作。我刚刚把它缩短了。
您可以使用in_array()
请参阅:-http://www.w3schools.com/php/func_array_in_array.asp