首页 > 解决方案 > count():参数必须是数组或对象,根据数组大小实现Countable error

问题描述

只有当返回的数组太长时,才会在下面的代码中产生这个错误。使用短数组(我不知道到底有多少)不会发生。

$phone_numbers = array();
if(!empty($_POST['phone_numbers']))
    $phone_numbers = json_decode($_POST['phone_numbers']);
    $phone_numbers_var = str_repeat('?,', count(json_decode($_POST['phone_numbers'])) - 1) . '?'; // <-- error line

count() 参数有限制吗?

标签: phparraysjsoncount

解决方案


首先检查你 $_POST['phone_numbers'] 得到了什么

请记住:

var_dump(count(null)); var_dump(count(false));

将输出:

Warning: count(): Parameter must be an array or an object that implements Countable in

我认为 PHP 7.2 版的计数有点奇怪......但你可以尝试这样的事情:

https://wiki.php.net/rfc/counting_non_countables

编辑 :

仅供评论:

$POST['phone_numbers'] = [165567, 545675, 655666];

如果您尝试这样做:

json_decode($POST['phone_numbers']);

将返回:

WARNING json_decode() expects parameter 1 to be string, array given on line number 4

并计数......你知道..只是这样做:

count($POST['phone_numbers']);

推荐阅读