【问题标题】:check if php array contains value [duplicate]检查php数组是否包含值[重复]
【发布时间】:2018-04-23 12:10:34
【问题描述】:

我有一个数组 $captions,我想检查里面是否至少有一个值。数组可能如下所示:

Array
(
    [0] => 84
    [1] => 
    [2] => 82
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
)

以及我检查是否有“超过0”,“超过1”的方法......

if (count($captions) > 0)   { echo '<br>bigger than 0';}
if (count($captions) === 1) {echo '<br>is 1';};
if (count($captions) > 1)   {echo '<br>gbigger than 1';};
if (count($captions) > 2)   {echo '<br>bigger than 2';}

但是:它给了我这个数组上面的结果:

bigger than 0
bigger than 1
bigger than 2

“大于2”不应该,因为数组只包含两个值?我哪里错了?

【问题讨论】:

  • 使用array_filter()
  • 它是计数数组的空值,所以使用 array_filter($array)

标签: php arrays


【解决方案1】:

你需要这样做(使用array_filter()):-

echo  "equal to" . count(array_filter($array));

输出:- https://eval.in/897055https://eval.in/897063

注意:- 在您的代码中,您也在计算空值,因此会出现歧义。您需要先删除空值,然后再进行计数。

【讨论】:

    【解决方案2】:

    使用php的array_filter函数

    array_filter($array)
    

    【讨论】:

      【解决方案3】:

      执行

      echo  count(array_filter($captions));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-13
        • 2019-08-10
        • 2019-10-03
        • 1970-01-01
        • 1970-01-01
        • 2020-12-11
        • 2013-10-27
        • 1970-01-01
        相关资源
        最近更新 更多