PHP count() Function (original) (raw)

Last Updated : 09 Apr, 2025

The count() function in PHP is used to count the number of elements in an array or the countable properties of an object. The function returns an integer value representing the number of items present.

**Syntax:

count($array, mode)

**In this syntax:

**Now, let us understand with the help of the example:

PHP `

ans=count(ans = count(ans=count(a); print($ans); ?>

`

**Counting Non-Countable Data Types

If you try to use count() on a non-countable data type (like a string or integer), it will return 0.

**Now, let us understand with the help of the example:

PHP `

`

Output

Warning: count(): Parameter must be an array or an object that implements Countable in /home/guest/sandbox/Solution.php on line 3 1 Warning: count(): Parameter must be an array or an object that impl...

Using count() with Objects

PHP objects that implement the Countable interface can also be counted. If an object implements the Countable interface, calling count() will return the number of elements defined by the object’s count() method.

**Now, let us understand with the help of the example:

PHP `

fruits); } } $basket = new FruitBasket(); echo count($basket); ?>

`

Recursive Count()

When working with multidimensional arrays, sometimes you want to count not only the elements at the top level but also the elements inside nested arrays. In this case, you can use the COUNT_RECURSIVE with the count() function to count all elements recursively, including those in nested arrays.

**Now, let us understand with the help of the example:

PHP `

array('orange', 'banana', 'apple'), 'cars' => array('honda', 'thar', 'skoda', 'hyundai')); echo "Recursive count: " . count($food, COUNT_RECURSIVE) . "\n"; echo "Normal count: " . count($food) . "\n"; ?>

`

Output

Recursive count: 9 Normal count: 2

Performance Considerations

While count() is generally fast, there are some considerations when using it:

Practical Use Cases for count()

The count() function is often used in scenarios such as:

Conclusion

The count() function is an essential tool in PHP for counting elements in arrays and objects. It simplifies many common tasks such as checking the size of arrays, validating input data, or implementing pagination.