【问题标题】:Don't print if array is not full如果数组未满则不打印
【发布时间】:2012-12-11 14:30:38
【问题描述】:

我有一个数组

array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');

如果里面只有苹果和橘子,我不想打印这个数组。我该怎么做?

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    你可以看看这个example here

    $haystack = array(...);
    
    $target = array('foo', 'bar');
    
    if(count(array_intersect($haystack, $target)) == count($target)){
        // all of $target is in $haystack
    }
    

    【讨论】:

      【解决方案2】:

      把苹果和橙子拿出来,看看有没有剩下的。

      $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)),可以说阅读起来更直观
      【解决方案3】:
      if (in_array('apples', $array) && in_array('oranges', $array) && count($array) == 2)
      {
          // Don't print array
      }
      

      【讨论】:

        【解决方案4】:

        如果你事先知道要进入数组的元素数量,那么你可以这样做:

        <?php
        $expectedCount = 5; //in this example, we are looking for five elements in our array
        if(count($array) == $expectedCount)
        {
            var_dump($array);
        }
        

        【讨论】:

          【解决方案5】:

          首先指定数组必须包含的最小元素数量,例如在本例中为 5 然后使用函数 count() 可以在http://php.net/manual/en/function.count.php找到参考

          if(count(array) >= 5)
          

          {

            //perform action 
          

          }

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-11
            • 1970-01-01
            • 1970-01-01
            • 2022-11-18
            • 1970-01-01
            相关资源
            最近更新 更多