Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Standard PHP Library and Classes

The Countable interface

Reference for the PHP Countable interface: make count() work on your own objects, the single count() method, return rules and common mistakes.

Countable is a one-method interface. When a class implements it, the built-in count() function (and its alias sizeof()) calls the object's count() method and returns the result. Without the interface, count($object) throws a TypeError.

Use it for collection-like classes (a cart, a result set, a typed list) so callers can ask for the size the same way they do for an array.

PHP
class Cart implements Countable
{
    public function count(): int
    {
        return 3;
    }
}

echo count(new Cart()); // 3

Try it

PHP A collection you can count()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Not countable, and COUNT_RECURSIVE

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
interface Countable
{
    public function count(): int;
}
Name Description
Countable::count() Takes no parameters. Returns the number of elements as an int.

Return value: an integer. count($object) returns exactly what your method returns.

Errors / Exceptions: count() throws TypeError for an argument that is neither an array nor a Countable.

Usage notes

  • Declare the return type : int. The interface requires it, so an implementation without a compatible return type is a fatal error.
  • Only count() uses it. Countable does not make an object iterable or array-like. Combine it with IteratorAggregate or ArrayAccess if you want those as well.
  • COUNT_RECURSIVE only descends into arrays. A Countable object inside an array counts as one element, not as its own count(); the second example prints 2 and then 5 (two elements plus the three nested values).
  • The result is not cached. count() runs your method every call, so make it cheap (return a stored counter or count($this->items)).
  • empty($object) ignores it. An object is always non-empty for empty(). Test count($obj) === 0 yourself.
  • Built-in classes such as ArrayObject, SplStack, SplObjectStorage and SplFixedArray already implement Countable.
  • Since PHP 8.0 count() on a non-countable value throws instead of warning.