<?php
$a = array(4, 5);
if (array_intersect($id_cart, $a) && array_diff($id_cart, $a))
{
echo "Yes\n";
} else {
echo "No\n";
}
Tested:
- 4,5: No
- 4,6: Yes
- 5,6: Yes
- 6,8: No
- 4,5,6,8,12,14: Yes
See array_intersect() and array_diff().
Intersect with array(4,5) tests for presence of either 4 or 5, because the result would be empty if neither value occurred in $id_cart.
Diff with array(4,5) tests for presence of another value besides 4 and 5, because the result would be empty if no value but 4 or 5 occurred in $id_cart.
Using count() to test for a non-empty array is unnecessary. An empty array evaluates as false in a condition.
Re Adriano's comment about simplicity or efficiency: PHP is tricky this way. Some functions are more efficient than others, so it's hard to say 2 function calls is better than 3. I tried running both my solution and Adriano's, and measuring elapsed time using microtime():
- Bill's solution: 6.25 seconds for 100000 iterations
- Adriano's solution: 5.59 seconds for 100000 iterations
So they're not equal, but Adriano's is only 10.5% faster. Close enough that I'd choose a solution for readability instead of for performance. If optimal performance were one's highest priority, one wouldn't be using PHP in the first place. :-)
FWIW, Adriano's other solution using foreach took 7.13 seconds for 100000 iterations.