crmpicco
crmpicco

Reputation: 17181

Check that an array includes at least a set of values in PHP

How can I check that the $courseAreas array includes at least "ayrshire" and "fife"?

I've tried the following code, but it does not work:

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

Upvotes: 0

Views: 38

Answers (3)

Robert
Robert

Reputation: 20286

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

You don't even need tenary operator because with > it's already boolean expression.

Edit:

I've noticed that your code works too. I've just shorten it.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212452

Try putting the ? true : false outside the braces

$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

But your original also seems to work perfectly well.... in what circumstances do you find that it fails?

Upvotes: 2

Rohan Kawade
Rohan Kawade

Reputation: 473

You can use in_array()

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

Upvotes: 0

Related Questions