d
Amit DhamuSoftware Engineer
 

is_countable

1 minute read 00000 views

PHP 7.2 introduces stricter checks when using count. Counting null or something that is not "countable" throws a warning:

Warning:  count(): Parameter must be an array or an object that implements Countable

We can check if something is countable by doing something like:

function is_countable($collection)
{
    return is_array($collection)
      || $collection instanceof \Countable
      || $collection instanceof \SimpleXMLElement
      || $collection instanceof \ResourceBundle;
}

PHP 7.3 actually introduced a native implementation of is_countable so the above is basically a polyfill for <= PHP 7.2.