How to check if something is countable?

三世轮回 提交于 2019-12-23 07:53:16

问题


I have a var: $a. I don't know what it is. I want to check if I can count it. Usually, with only array, I can do this:

if (is_array($a)) {
    echo count($a);
}

But some other things are countable. Let's say a Illuminate\Support\Collection is countable with Laravel:

if ($a instanceof \Illuminate\Support\Collection) {
    echo count($a);
}

But is there something to do both thing in one (and maybe work with some other countable instances). Something like:

if (is_countable($a)) {
    echo count($a);
}

Does this kind of function exists? Did I miss something?


回答1:


For previous PHP versions, you can use this

if (is_array($foo) || $foo instanceof Countable) {
    return count($foo);
}

or you could also implement a sort of polyfill for that like this

if (!function_exists('is_countable')) {

    function is_countable($c) {
        return is_array($c) || $c instanceof Countable;
    }

}

Note that this polyfill isn't something that I came up with, but rather pulled directly from the RFC for the new function proposal https://wiki.php.net/rfc/is-countable




回答2:


PHP 7.3

According to the documentation, You can use is_countable function:

if (is_countable($a)) {
    echo count($a);
}


来源:https://stackoverflow.com/questions/42899605/how-to-check-if-something-is-countable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!