is_countable

(PHP 7 >= 7.3.0, PHP 8)

is_countable 验证变量内容是否为可数值

说明

is_countable(mixed $value): bool

验证变量的内容是数组还是实现了 Countable 接口的对象

参数

value

需要检查的值

返回值

如果 value 是可数值,返回 true,否则返回 false

更新日志

版本 说明
7.3.0 is_countable() 被添加。

示例

示例 #1 is_countable() 示例

<?php
var_dump
(is_countable([1, 2, 3])); // bool(true)
var_dump(is_countable(new ArrayIterator(['foo', 'bar', 'baz']))); // bool(true)
var_dump(is_countable(new ArrayIterator())); // bool(true)
var_dump(is_countable(new stdClass())); // bool(false)

参见

add a note add a note

User Contributed Notes 6 notes

up
40
info at arisendrake dot de
5 years ago
If you are unable to upgrade to PHP 7.3 (not released at the time of writing), you can use this simple polyfill:

<?php
if (!function_exists('is_countable')) {
    function
is_countable($var) {
        return (
is_array($var) || $var instanceof Countable);
    }
}
?>
up
3
renic
4 years ago
be wary of using is_object($var) and assuming that the object has implemented Countable.  Not all objects are countable directly with count().
up
2
Anonymous
3 years ago
Fixed polyfill:
<?php
if (! function_exists('is_countable')) {
   
/**
      * @param mixed $value The value to check
      * @return bool
      */
   
function is_countable($value): bool
   
{
        return
is_array($value) || (is_object($value) && $value instanceof Countable);
    }
}
?>
up
-2
info at ensostudio dot ru
3 years ago
Note: if is_countable() return true is does not guarantee that the it can be calculated recursively and correctly:
<?php
$iterator
= new ArrayIterator(['one', 'two', new ArrayIterator(['three', 'four'])]);
var_dump(is_countable($iterator), count($iterator, COUNT_RECURSIVE));
// return TRUE and 3!
?>
up
0
danmichaelo at gmail dot com
4 years ago
Note that a polyfill for this method is also provided by the symfony/polyfill project.
up
-8
deoomen
4 years ago
Polyfill written by arisendrake is not quite good. It return FALSE when checking an Simple XML Node but count() works properly on PHP 7.1 and 7.3.
Better is this one:

<?php
if (version_compare(PHP_VERSION, "7.3") < 0 && !function_exists("is_countable")) {
    function
is_countable($var): bool
   
{
        return (
is_array($var) || is_object($var) || is_iterable($var) || $var instanceof Countable);
    }
}
?>
To Top