PHP 7.3: Introduced is_countable() function
PHP 7.2 deprecated quite a lot of functions and buggy use cases. In PHP 7.2, if you call count()
on a variable that is not "countable", PHP shows a warning about it. A common fix was to check if the given variable is "countable" before calling count()
on it.
A "countable" variable is either an array, or an object of a class that implements \Countable
interface. Because there can be a lot of boilerplate code, PHP 7.3 now has a new is_countable()
function that returns true
if the passed variable is... well... countable.
Polyfill
I have put together a polyfill for is_countable() if you want to use this on pre-PHP 7.3 code.
Here is a simple yet conforming polyfill if you cannot use PHP 7.3 immediately and prefer to not use the package above.
if (!function_exists('is_countable')) {
function is_countable($var) {
return is_array($var)
|| $var instanceof Countable
|| $var instanceof ResourceBundle
|| $var instanceof SimpleXmlElement;
}
}
Backwards compatibility impact
Unless you have declared your own is_countable
function, there shouldn't be any issues.