• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • count()

    (PHP 4, PHP 5, PHP 7)

    计算数组中的单元数目,或对象中的属性个数

    说明

    count(mixed $array_or_countable[,int $mode= COUNT_NORMAL]): int

    统计出数组里的所有元素的数量,或者对象里的东西。

    对于对象,如果安装了SPL,可以通过实现Countable接口对count()挂钩(hook)。该接口只有一个方法Countable::count(),此方法为count()函数返回值。

    关于 PHP 中如何实现和使用数组可以参考手册中数组章节中的详细描述。

    参数

    $array_or_countable

    数组或者Countable对象。

    $mode

    如果可选的$mode参数设为COUNT_RECURSIVE(或 1),count()将递归地对数组计数。对计算多维数组的所有单元尤其有用。

    Caution

    count()能检测递归来避免无限循环,但每次出现时会产生E_WARNING错误(如果 array 不止一次包含了自身)并返回大于预期的统计数字。

    返回值

    返回$array_or_countable中的单元数目。如果参数既不是数组,也不是实现Countable接口的对象,将返回1。有个例外:如果$array_or_countableNULL则结果是0

    范例

    Example #1count()例子

    <?php
    $a[0] = 1;
    $a[1] = 3;
    $a[2] = 5;
    var_dump(count($a));
    $b[0]  = 7;
    $b[5]  = 9;
    $b[10] = 11;
    var_dump(count($b));
    var_dump(count(null));
    var_dump(count(false));
    ?>
    

    以上例程会输出:

    int(3)
    int(3)
    Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // PHP 7.2 起
    int(0)
    Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 // PHP 7.2 起
    int(1)
    

    递归count()例子

    <?php
    $food = array('fruits' => array('orange', 'banana', 'apple'),
                  'veggie' => array('carrot', 'collard', 'pea'));
    // recursive count
    echo count($food, COUNT_RECURSIVE); // output 8
    // normal count
    echo count($food); // output 2
    ?>
    

    更新日志

    版本说明
    7.2.0当无效的 countable 类型传递给$array_or_countable参数时,count()会产生警告。

    参见

    [Editor's note: array at from dot pl had pointed out that count() is a cheap operation; however, there's still the function call overhead.]
    If you want to run through large arrays don't use count() function in the loops , its a over head in performance, copy the count() value into a variable and use that value in loops for a better performance.
    Eg:
    // Bad approach
    for($i=0;$i<count($some_arr);$i++)
    {
      // calculations
    }
    // Good approach
    $arr_length = count($some_arr);
    for($i=0;$i<$arr_length;$i++)
    {
      // calculations
    }
    to end the debate: count() is the same as empty()
    test code below:
    results on my computer:
    count : double(0.81396999359131)
    empty : double(0.81621310710907)
    using isset($test[0]) is a bit slower than empty;
    test without adding value to the array in function ****Test: still the same.
    <?php
    function average(array $test)
    {
      $sum = 0;
      foreach($test as $value) {
        $sum += $value;
      }
      return $sum;
    }
    function countTest(array $test)
    {
      $i = 0;
      while ($i++ < 1000000) {
        count($test);
        $test["lol$i"] = "teset$i";
      }
    }
    function emptyTest(array $test)
    {
      $i = 0;
      while ($i++ < 1000000) {
        empty($test);
        $test["lol$i"] = "teset$i";
      }
    }
    $test = [];
    $i = 0;
    while ($i++ < 20000000) {
      $test[] = $i;
    }
    $j = 10;
    $value = $j;
    $count = [];
    $isEmpty = [];
    while ($j--) {
      $time = microtime(true);
      countTest($test);
      $count[] = microtime(true) - $time;
      $time = microtime(true);
      emptyTest($test);
      $isEmpty[] = microtime(true) - $time;
    }
    var_dump(average($count) / $value);
    var_dump(average($isEmpty) / $value);
    If you are on PHP 7.2+, you need to be aware of "Changelog" and use something like this:
    <?php
    $countFruits = is_array($countFruits) || $countFruits instanceof Countable ? count($countFruits) : 0;
    ?>
    You can organize your code to ensure that the variable is an array, or you can extend the Countable so that you don't have to do this check.
    My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).
    <?php
     function getArrCount ($arr, $depth=1) {
       if (!is_array($arr) || !$depth) return 0;
         
       $res=count($arr);
         
       foreach ($arr as $in_ar)
         $res+=getArrCount($in_ar, $depth-1);
       
       return $res;
     }
    ?>
    
    You can not get collect sub array count when there is only one sub array in an array: 
    $a = array ( array ('a','b','c','d'));
    $b = array ( array ('a','b','c','d'), array ('e','f','g','h'));
    echo count($a); // 4 NOT 1, expect 1
    echo count($b); // 2,  expected
    I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.
    // $limit is set to the number of recursions
    <?php
    function count_recursive ($array, $limit) {
      $count = 0;
      foreach ($array as $id => $_array) {
        if (is_array ($_array) && $limit > 0) {
          $count += count_recursive ($_array, $limit - 1);
        } else {
          $count += 1;
        }
      }
      return $count;
    }
    ?>
    
    All the previous recursive count solutions with $depth option would not avoid infinite loops in case the array contains itself more than once.
    Here's a working solution:
    <?php
      /**
       * Recursively count elements in an array. Behaves exactly the same as native
       * count() function with the $depth option. Meaning it will also add +1 to the
       * total count, for the parent element, and not only counting its children.
       * @param $arr
       * @param int $depth
       * @param int $i (internal)
       * @return int
       */
      public static function countRecursive(&$arr, $depth = 0, $i = 0) {
        $i++;
        /**
         * In case the depth is 0, use the native count function
         */
        if (empty($depth)) {
          return count($arr, COUNT_RECURSIVE);
        }
        $count = 0;
        /**
         * This can occur only the first time when the method is called and $arr is not an array
         */
        if (!is_array($arr)) {
          return count($arr);
        }
        // if this key is present, it means you already walked this array
        if (isset($arr['__been_here'])) {
          return 0;
        }
        $arr['__been_here'] = true;
        foreach ($arr as $key => &$value) {
          if ($key !== '__been_here') {
            if (is_array($value) && $depth > $i) {
              $count += self::countRecursive($value, $depth, $i);
            }
            $count++;
          }
        }
        // you need to unset it when done because you're working with a reference...
        unset($arr['__been_here']);
        return $count;
      }
    ?>
    
    A function of one line to find the number of elements that are not arrays, recursively :
    function count_elt($array, &$count=0){
     foreach($array as $v) if(is_array($v)) count_elt($v,$count); else ++$count;
     return $count;
    }
    For a Non Countable Objects
    $count = count($data);
    print "Count: $count\n";
    Warning: count(): Parameter must be an array or an object that implements Countable in example.php on line 159
    #Quick fix is to just cast the non-countable object as an array.. 
    $count = count((array) $data);
    print "Count: $count\n";
    Count: 250
    Get maxWidth and maxHeight of a two dimensional array..?
    Note:
    1st dimension = Y (height)
    2nd dimension = X (width)
    e.g. rows and cols in database result arrays
    <?php
    $TwoDimensionalArray = array( 0 => array( 'key' => 'value', ...), ... );
    ?>
    So for Y (maxHeight) 
    <?php
    $maxHeight = count( $TwoDimensionalArray )
    ?>
    And for X (maxWidth)
    <?php
    $maxWidth = max( array_map( 'count', $TwoDimensionalArray ) );
    ?>
    Simple? ;-)
    As I see in many codes, don't use count to iterate through array.
    Onlyranga says you could declare a variable to store it before the for loop.
    I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.
    You can do it in the for loop too, so you don't have to "search" where the variable is set.
    e.g.
    <?php
      $array = [1, 5, 'element'];
      for($i = 0, $c = count($array); $i < $c; $i++)
        var_dump($array[$i]);
    ?>
    
    You can not get collect sub array count when use the key on only one sub array in an array: 
    $a = array("a"=>"appple", b"=>array('a'=>array(1,2,3),'b'=>array(1,2,3)));
    $b = array("a"=>"appple", "b"=>array(array('a'=>array(1,2,3),'b'=>array(1,2,3)), array(1,2,3),'b'=>array(1,2,3)), array('a'=>array(1,2,3),'b'=>array(1,2,3))));
    echo count($a['b']); // 2 NOT 1, expect 1
    echo count($b['b']); // 3,  expected
    About 2d arrays, you have many way to count elements :
    <?php
    $MyArray = array ( array(1,2,3),
              1,
              'a',
              array('a','b','c','d') );
    // All elements
    echo count($MyArray ,COUNT_RECURSIVE); // output 11 (9 values + 2 arrays)
    // First level elements
    echo count($MyArray );         // output 4 (2 values+ 2 arrays)
    // Both level values, but only values
    echo(array_sum(array_map('count',$MyArray ))); //output 9 (9 values)
    // Only second level values
    echo (count($MyArray ,COUNT_RECURSIVE)-count($MyArray )); //output 7 ((all elements) - (first elements))
    ?>
    
    Criada para contar quantos níveis um array multidimensional possui.
    function count_multiLevel($matrix, $_LEVEL = 0){
        
        /* Variáveis de recursão */
        $_COUNT = $_LEVEL;
        
        /* Verifica se o ARRAY foi instanciado */
        if (is_setVar($matrix)){
          
          /* Verifica se a variável é um ARRAY */
          if(is_array($matrix)){
            
            /* Loop de elementos da matriz*/
            foreach ($matrix as $elements => $value) {
              
              /* Auxiliar para verificação posterior */
              $_AUX = $_COUNT; 
              
              /* Verifiando os Nós */
              if (is_array($matrix[$elements])) {
                $_COUNT = count_multiLevel($matrix[$elements], $_LEVEL+1);  
              }
              /* Cereja do bolo */
              if($_AUX > $_COUNT)
                $_COUNT = $_AUX;
            }
            /* Retorn do resultado da operação */
            return $_COUNT;
            
          }else{
            /* Em casos que o valor passado não seja uma matriz/array */
            return -1;
          }
        }
      }

    上篇:compact()

    下篇:current()