开发者

Does array_a contain all elements of array_b

If this is $array_b

$array_b = array('red', 'green', 'blue'); 

What's an efficient way to compare it to $array_a and get a boolean as to whether $array_a contains all elements of the above $array_b.

This is the output I'm trying to get to

//false, because it's missing the red from `$array_b`
$array_a = array('green', 'blue'); 

//true, because it contains all 3 from `$array_b`
$array_a = array('red', 'green', 'blue');     

//t开发者_如何学JAVArue, because it contains all 3 from `$array_b`
//even though there's an extra orange and cyan
$array_a = array('red', 'green', 'blue', 'orange', 'cyan'); 

What's a good way to do this without nasty nested loops that are hard to keep track of?


if (count(array_intersect($array_a, $array_b)) == count($array_b)) {
    ...
}

or as function

function function_name($array_a, $array_b) {
    return count(array_intersect($array_a, $array_b)) == count($array_b);
}


$boolean = count(array_diff($array_b, $array_a)) == 0 ? true : false;


empty() is faster than count(), and diff is faster than intersect.

$diff=array_diff($array_a, $array_b);
if(empty($diff))
{
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜