【发布时间】:2012-12-11 14:30:38
【问题描述】:
我有一个数组
array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');
如果里面只有苹果和橘子,我不想打印这个数组。我该怎么做?
【问题讨论】:
我有一个数组
array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');
如果里面只有苹果和橘子,我不想打印这个数组。我该怎么做?
【问题讨论】:
你可以看看这个example here:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
【讨论】:
把苹果和橙子拿出来,看看有没有剩下的。
$arr = array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');
$arrDiff = array_diff($arr, array('apples', 'oranges')); //take out the apples and oranges
if(!empty($arrDiff)) //there's something other than apples and oranges in the array
print_r($arr);
【讨论】:
if (!empty($arrDiff)),可以说阅读起来更直观
if (in_array('apples', $array) && in_array('oranges', $array) && count($array) == 2)
{
// Don't print array
}
【讨论】:
如果你事先知道要进入数组的元素数量,那么你可以这样做:
<?php
$expectedCount = 5; //in this example, we are looking for five elements in our array
if(count($array) == $expectedCount)
{
var_dump($array);
}
【讨论】:
首先指定数组必须包含的最小元素数量,例如在本例中为 5 然后使用函数 count() 可以在http://php.net/manual/en/function.count.php找到参考
if(count(array) >= 5)
{
//perform action
}
【讨论】: