How to check if something is countable?

前端 未结 2 815
余生分开走
余生分开走 2021-01-17 14:05

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)) {
             


        
相关标签:
2条回答
  • 2021-01-17 14:33

    PHP 7.3

    According to the documentation, You can use is_countable function:

    if (is_countable($a)) {
        echo count($a);
    }
    
    0 讨论(0)
  • 2021-01-17 14:39

    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

    0 讨论(0)
提交回复
热议问题