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:
我有一个var: $a。我不知道是什么。我想看看能不能数一下。通常,只有数组,我可以这样做:
if (is_array($a)) {
echo count($a);
}
But some other things are countable. Let's say a Illuminate\Support\Collection
is countable with Laravel:
但是其他的一些事情是可以计算的。让我们假设一个照明\支持收集是可数的与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?
这种函数存在吗?我错过什么了吗?
2 个解决方案
#1
3
For previous PHP versions, you can use this
对于以前的PHP版本,您可以使用它
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;
}
}
#2
2
PHP 7.3
According to the documentation, You can use is_countable
function:
根据文件,可以使用is_countable函数:
if (is_countable($a)) {
echo count($a);
}
#1
3
For previous PHP versions, you can use this
对于以前的PHP版本,您可以使用它
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;
}
}
#2
2
PHP 7.3
According to the documentation, You can use is_countable
function:
根据文件,可以使用is_countable函数:
if (is_countable($a)) {
echo count($a);
}