PHP 7.2 count() function is not working

帅比萌擦擦* 提交于 2019-12-10 23:47:01

问题


I have a working php application and it is running fine on php 7.0 version. But when I upgrade a php version to 7.2. I am getting this error:

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

I am getting errors on code where I am comparing my data with count function. For example this is my code:

$keytest = KeyUser::where('key', '=', $key)->first();
 if (count($keytest) == 1) {
   //logic ... 
  }

I am using laravel where I am running a query and counting it if it is equal to 1 then logic should work.

So my problem is I have written this kind of logic on many controllers and if I have to change everything one by one it could become nightmare. So is there any way where I can write a global function to make count work as it was working in php older version. What can be the easiest fix.


回答1:


This problem can be handle using disable error handling. Please refer this link for solution: Laravel not compatiable with php 7.2

Here I found a solution to your problem simply write this code inside your controller or if you want to make it work for whole application write this code in route.php:

 //app/Http/routes.php

 if (version_compare(PHP_VERSION, '7.2.0', '>=')) {
// Ignores notices and reports all other kinds... and warnings
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
// error_reporting(E_ALL ^ E_WARNING); // Maybe this is enough
}

I know this is not the best solution but it can be a good hack.




回答2:


It's solved when you change your code:

$keytest = KeyUser::where('key', '=', $key)->first();
if ($keytest) {
   //logic ... 
}


来源:https://stackoverflow.com/questions/50667333/php-7-2-count-function-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!