phpday 2027 - Call for Papers

count

(PHP 4, PHP 5, PHP 7, PHP 8)

count — Conta tutti gli elementi di un array o di un oggetto Countable

Descrizione

function count(Countable|array $value, int $mode = COUNT_NORMAL): int

Conta tutti gli elementi di un array, quando viene usata con un array. Quando viene usata con un oggetto che implementa l'interfaccia Countable, restituisce il valore restituito dal metodo Countable::count().

Elenco dei parametri

value

Un array o un oggetto Countable.

mode

Se il parametro opzionale mode è impostato a COUNT_RECURSIVE (o 1), count() conterà ricorsivamente l'array. È particolarmente utile per contare tutti gli elementi di un array multidimensionale.

Attenzione

count() è in grado di rilevare la ricorsione per evitare un ciclo infinito, ma emetterà un E_WARNING ogni volta che lo fa (nel caso in cui l'array contenga se stesso più di una volta) e restituirà un conteggio più alto di quanto ci si potrebbe aspettare.

Valori restituiti

Restituisce il numero di elementi di value. Prima di PHP 8.0.0, se il parametro non era né un array né un object che implementa l'interfaccia Countable, veniva restituito 1, a meno che value non fosse null, nel qual caso veniva restituito 0.

Errori/Eccezioni

Lancia un ValueError se mode non è COUNT_NORMAL o COUNT_RECURSIVE.

Log delle modifiche

Versione Descrizione
8.0.0 Ora lancia un ValueError se mode non è COUNT_NORMAL o COUNT_RECURSIVE.
8.0.0 count() ora lancia un TypeError per tipi non contabili non validi passati al parametro value.
7.2.0 count() ora emette un avviso per tipi non contabili non validi passati al parametro value.

Esempi

Example #1 Esempio di count()

<?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));
?>

Il precedente esempio visualizzerà:

int(3)
int(3)

Example #2 Esempio di count() con valori né Countable né array (cattivo esempio - da non fare)

<?php
$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));

var_dump(count(null));

var_dump(count(false));
?>

Il precedente esempio visualizzerà:

int(3)

Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12

Example #3 Esempio di count() ricorsivo

<?php
$food = array('frutta' => array('arancia', 'banana', 'mela'),
              'verdura' => array('carota', 'cavolo', 'pisello'));

// conteggio ricorsivo
var_dump(count($food, COUNT_RECURSIVE));

// conteggio normale
var_dump(count($food));

?>

Il precedente esempio visualizzerà:

int(8)
int(2)

Example #4 Oggetto Countable

<?php
class CountOfMethods implements Countable
{
    private function someMethod()
    {
    }

    public function count(): int
    {
        return count(get_class_methods($this));
    }
}

$obj = new CountOfMethods();
var_dump(count($obj));
?>

Il precedente esempio visualizzerà:

int(2)

Vedere anche:

  • is_array() - Verifica se una variabile è un array
  • isset() - Verifica se una variabile è dichiarata ed è diversa da null
  • empty() - Determina se una variabile è vuota
  • strlen() - Restituisce la lunghezza di una stringa
  • is_countable() - Verify that the contents of a variable is a countable value
  • Arrays

+add a note

User Contributed Notes 6 notes

up
143
onlyranga at gmail dot com
12 years ago
[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
}
up
5
lucasfsmartins at gmail dot com
7 years ago
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.
up
11
danny at dannymendel dot com
19 years ago
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;
}
?>
up
11
alexandr at vladykin dot pp dot ru
20 years ago
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;
  }
?>
up
-1
Anonymous
7 years ago
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
up
0
pied-pierre
11 years ago
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;
}
To Top