【问题标题】:PHP 7.4 - Warning: count(): Parameter must be an arrayPHP 7.4 - 警告:count():参数必须是数组
【发布时间】:2020-08-27 22:17:06
【问题描述】:

我刚刚将我的 PHP 版本从 5.6 升级到了 7.4。我在我的页面中使用了 count() 函数,例如:

$watch_server_count  = count($watch_server);
if ($watch_server_count > 0) {
    foreach ($watch_server->table as $key=> $watch_server_rows) {

    }
}

警告:count():参数必须是数组或实现了Countable的对象...

【问题讨论】:

标签: php count php-7 php-7.4 countable


【解决方案1】:

从 PHP 7.1 开始,您可以在执行foreach 之前使用is_iterable

(PHP 7 >= 7.1.0) is_iterable — 验证变量的内容是否为可迭代值

https://www.php.net/manual/en/function.is-iterable.php

所以代码将如下所示:

if ( is_iterable($watch_server->table) ) {
    foreach ($watch_server->table as $key=> $watch_server_rows) {
        //
    }
}

【讨论】:

    【解决方案2】:

    你可以试试这个方法。 is_countable

    https://www.php.net/manual/en/function.is-countable.php

    if ( is_countable($watch_server->table) ) {
        foreach ($watch_server->table as $key=> $watch_server_rows) {
            ...
        }
    }
    

    【讨论】:

    • 嗨,Mehmet,欢迎来到 Stackoverflow。如果您发布答案,请检查是否已经有其他答案涵盖相同的代码。在这种情况下,Redy S 提供了另一个答案。此外,您的答案可能是错误的,因为并非所有实现 Countable 接口的对象都提供了必要的迭代方法
    猜你喜欢
    • 2019-08-15
    • 2019-10-18
    • 2019-06-20
    • 2018-12-19
    • 1970-01-01
    • 2019-01-06
    • 2020-01-18
    • 2020-01-26
    • 2020-01-27
    相关资源
    最近更新 更多