14

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?

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • 1
    maybe http://stackoverflow.com/questions/12346479/how-to-check-for-arrayness-in-php ? with `$var instanceof Countable` – Scuzzy Mar 20 '17 at 09:16
  • @Scuzzy's way is a good start and maybe is worth also trying to see if is traversable: http://php.net/manual/en/class.traversable.php – Edwin Mar 20 '17 at 09:24
  • http://php.net/manual/en/function.count.php – bxN5 Mar 20 '17 at 09:46
  • Good news. It is looking like PHP 7.3 is aiming to have a built in function for this https://wiki.php.net/rfc/is-countable – Antony D'Andrea Mar 08 '18 at 10:29

2 Answers2

29

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

Brian Leishman
  • 8,155
  • 11
  • 57
  • 93
18

PHP 7.3

According to the documentation, You can use is_countable function:

if (is_countable($a)) {
    echo count($a);
}
kjones
  • 1,339
  • 1
  • 13
  • 28
rap-2-h
  • 30,204
  • 37
  • 167
  • 263