1.2.1352. Use is_countable

is_countable() checks if a variables holds a value that can be counted. It is recommended to use it before calling count().

is_countable() accepts arrays and object whose class implements `countable <https://www.php.net/countable>`_.

<?php

function foo($arg) {
    if (!is_countable($arg)) {
        // $arg cannot be passed to count()
        return 0
    }
    return count($arg);
}

function bar($arg) {
    if (!is_array($arg) and !$x instanceof \Countable) {
        // $arg cannot be passed to count()
        return 0
    }

    return count($arg);
}

?>

See also PHP RFC: is_countable.

1.2.1352.1. Suggestions

  • Use is_countable()

  • Create a compatibility function that replaces is_countable() until the code is ready for PHP 7.3

1.2.1352.2. Specs

Short name

Php/CouldUseIsCountable

Rulesets

All, Changed Behavior, Suggestions

Exakat since

1.3.8

PHP Version

With PHP 7.3 and more recent

Severity

Time To Fix

Precision

High

Features

array, countable

Available in

Entreprise Edition, Exakat Cloud