检查数组是否包含PHP中的至少一组值

时间:2015-11-27 12:04:57

标签: php arrays array-intersect

如何检查$courseAreas数组至少包含 " ayrshire" 和" fife"?

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

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

3 个答案:

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

Seems to work

但是你的原作似乎也能很好地工作......在什么情况下你会发现它失败了?

答案 1 :(得分:1)

$courseAreas = array('ayrshire', 'fife', 'cheshire', 'lanarkshire');
$includesAyrshireAndFife = count(array_intersect(array('ayrshire', 'fife'), $courseAreas)) > 1;

你甚至不需要tenary运营商因为>它已经是布尔表达式。

修改

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

答案 2 :(得分:0)

您可以使用in_array()

请参阅: - http://www.w3schools.com/php/func_array_in_array.asp