# `is_countable()`

> Section in “New and Extended Functionality › Language Features” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/language-features/is_countable/>

The `count()` function can be used to either count the elements of an array or “something inside an object”. The latter means that the `count()` function delegates the actual counting operation a method when used on an object. This object needs to implement the `Countable` interface for this to work:

``` php
$array = [1, 2, 3];
var_dump(count($array));

$object = new stdClass;
var_dump(count($object));

class C implements Countable
{
    public function count(): int
    {
        return 0;
    }
}

$object = new C;
var_dump(count($object));
```

Using `count()` on an object that does not implement the `Countable` interface returns `1` and triggers a warning. Executing the code shown above will print the output shown below:

    int(3)
    PHP Warning: count(): Parameter must be an array or an object
    that implements Countable in ...
    int(1)
    int(0)

In previous versions of PHP `is_array()` and `instanceof` had to be used to determine whether a variable can be passed to `count()` without triggering that warning:

``` php
if (is_array($variable) || $variable instanceof Countable) {
    // count($variable) can be used
}
```

Thanks to the new `is_countable()` function, the code shown above can now be replaced with

``` php
if (is_countable($variable)) {
    // count($variable) can be used
}
```

---

Previous: [Countable Interface and Internal Classes](https://php7explained.com/new-and-extended-functionality/language-features/countable-interface-and-internal-classes/index.html.md) | Next: [Asynchronous Signal Handling](https://php7explained.com/new-and-extended-functionality/language-features/asynchronous-signal-handling/index.html.md)
