0

如何检查$courseAreas数组是否至少包含“ayrshire”和“fife”?

我尝试了以下代码,但它不起作用:

$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = (count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) >= 2 ? true : false);
4

3 回答 3

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);

似乎工作

但是您的原件似乎也运行良好....在什么情况下您发现它失败了?

于 2015-11-27T12:11:28.287 回答
1
$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) > 1;

您甚至不需要三元运算符,因为 > 它已经是布尔表达式。

编辑

我注意到你的代码也有效。我只是缩短了它。

于 2015-11-27T12:12:59.833 回答
0

您可以使用in_array()

见:- http://www.w3schools.com/php/func_array_in_array.asp

于 2015-11-27T12:08:25.087 回答