Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

count

Returns the number of elements in an array.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$valueCountable|arrayAn array or an object implementing the Countable interface.
$modeintWith `COUNT_RECURSIVE`, elements of nested arrays are counted too.

Return value

intThe number of elements.

Examples

A regular and an empty array:

<?php
 
echo count(['a', 'b', 'c']), "\n";
echo count([]);

Output:

3
0

Checking that an array is not empty:

<?php
 
$items = ['tea'];
 
var_dump(count($items) > 0);

Output:

bool(true)

Notes

Passing something that is neither an array nor a Countable object — a string or null, for example — throws a type error.

See also

  • array_sum — Returns the sum of the values in an array.
  • in_array — Checks whether a value exists in an array.

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.