Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
rap-2-h Avatar asked Mar 20 '17 09:03

rap-2-h


People also ask

How do you know if something is countable?

In mathematics, a set is said to be countable if its elements can be "numbered" using the natural numbers. More precisely, this means that there exists a one-to-one mapping from this set to (not necessarily onto) the set of natural numbers. A countable set is either finite or countably infinite.

How do you know if a set is uncountable?

In mathematics, an uncountable set (or uncountably infinite set) is an infinite set that contains too many elements to be countable. The uncountability of a set is closely related to its cardinal number: a set is uncountable if its cardinal number is larger than that of the set of all natural numbers.

What makes a set countable?

A set is said to be countable, if you can make a list of its members. By a list we mean that you can find a first member, a second one, and so on, and eventually assign to each member an integer of its own, perhaps going on forever. The natural numbers are themselves countable- you can assign each integer to itself.

How do you prove an integer is countable?

By Corollary 4 the set of all even integers is countable, as is the set of all multiples of three, the set of all cubes of integers, etc. It follows from Corollary 4 that once a set can be put into 1-1 correspondence with any subset of the integers, it is countable.


2 Answers

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

like image 169
Brian Leishman Avatar answered Sep 27 '22 18:09

Brian Leishman


PHP 7.3

According to the documentation, You can use is_countable function:

if (is_countable($a)) {
    echo count($a);
}
like image 41
rap-2-h Avatar answered Sep 27 '22 20:09

rap-2-h