PHP count() Function

Quick summary: The PHP count() function counts the number of elements in an array or Countable object.

PHP count() Syntax

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

PHP count() Basic examples

var_dump(count([1,2,3]));
PHP
Output:
int(3)

Counts the number of elements in an array.

PHP count() Real-world usage

$items = [];
if (count($items) === 0) {
    echo 'Empty';
}
PHP
Output:
Empty

Checks if an array is empty.

PHP count() Edge cases

var_dump(count(null));
PHP
Output:
Warning: count(): Parameter must be an array or an object that implements Countable

count() expects an array or Countable.

PHP count() Common mistakes

Using count in loops repeatedly

Calling count() inside loops is inefficient.

Incorrect
for ($i=0; $i<count($arr); $i++) {}
Correct
$len=count($arr); for ($i=0; $i<$len; $i++) {}

Store the count result before looping.

PHP count() Frequently Asked Questions

What does count() do in PHP?

count() returns the number of elements in an array or Countable object.

What is the syntax of count()?

count(mixed $value, int $mode = COUNT_NORMAL): int

What is COUNT_RECURSIVE?

Counts all elements in multi-dimensional arrays.

Does count() modify array?

No.

Can count() be used on objects?

Yes, if object implements Countable.

What happens if not countable?

Returns 1 or triggers warning in strict types.

Use case?

Checking array size.

Performance?

Very fast.

Difference from sizeof()?

They are identical.

Can count nested arrays?

Yes with COUNT_RECURSIVE.

Returns 0 for empty array?

Yes.

Best practice?

Use count() over sizeof().

PHP count() Related PHP Functions