How to check if something is countable?
Asked Answered
C

2

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?

Circumfluent answered 20/3, 2017 at 9:12 Comment(4)
maybe #12346979 ? with $var instanceof CountablePatience
@Scuzzy's way is a good start and maybe is worth also trying to see if is traversable: php.net/manual/en/class.traversable.phpSettera
php.net/manual/en/function.count.phpJake
Good news. It is looking like PHP 7.3 is aiming to have a built in function for this wiki.php.net/rfc/is-countableSnowslide
C
18

PHP 7.3

According to the documentation, You can use is_countable function:

if (is_countable($a)) {
    echo count($a);
}
Circumfluent answered 9/3, 2018 at 8:44 Comment(3)
That's for a version of PHP that isn't released yet :DBranton
PHP 7.3 Alpha 1 is now released. Please also note: PHP 7.3 SHOULD NOT be used in production. Please wait for Production Ready version to save yourself for the hassle.Footgear
We're at 7.4 now, so this answer is now more than acceptable.Ridicule
H
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

Hysteric answered 18/4, 2018 at 13:40 Comment(0)
C
18

PHP 7.3

According to the documentation, You can use is_countable function:

if (is_countable($a)) {
    echo count($a);
}
Circumfluent answered 9/3, 2018 at 8:44 Comment(3)
That's for a version of PHP that isn't released yet :DBranton
PHP 7.3 Alpha 1 is now released. Please also note: PHP 7.3 SHOULD NOT be used in production. Please wait for Production Ready version to save yourself for the hassle.Footgear
We're at 7.4 now, so this answer is now more than acceptable.Ridicule

© 2022 - 2024 — McMap. All rights reserved.