Search code examples
phparrayslaravellaravel-collection

How to check if something is countable?


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?


Solution

  • PHP 7.3

    According to the documentation, You can use is_countable function:

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