Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

Countable

The interface of objects that can be passed to `count()`.

Syntax

class Name implements Countable

Return value

intThe `count()` method returns the number of elements.

Examples

A cart that can be counted:

<?php
 
class Cart implements Countable
{
    private array $items = ['tea', 'coffee', 'juice'];
 
    public function count(): int
    {
        return count($this->items);
    }
}
 
echo count(new Cart());

Output:

3

Notes

Without the interface a count($object) call ends with a TypeError.

See also

  • count — Returns the number of elements in an array.
  • is_countable — Checks whether a value can be passed to `count()`.
  • ArrayAccess — The interface of objects accessed with square brackets.

In the tutorial

  • Built-in interfaces — PHP interfaces that teach an object to behave like an array — Countable, IteratorAggregate, ArrayAccess, JsonSerializable and Stringable.

Thanks for reading!

Donate to the site — we work hard for you.