Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any way to make array count in PHP $_POST work without prefixing array with it?

So I upgraded to PHP 8 and ran my script which gave me this error:

Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given in C:\xampp\htdocs\app\includes\functions\create_session.php:78
Stack trace:
#0 C:\xampp\htdocs\public\modules\FDO\front_desk.php(508): Session->check_subfeature_access(22, 0)
#1 {main} thrown in C:\xampp\htdocs\app\includes\functions\create_session.php on line 78

Which turned out to be due to a new update in PHP 8 that doesn’t allow non-array values to be used in the count function and throws a fatal error stopping the further script execution. For example, if you have a $_POST['checkboxes_checked'] and you do count($_POST['checkboxes_checked']) then it will give the above error because by default it doesn’t recognize it as an array. To fix this error, you can do: count((array)$_POST['checkboxes_checked'])), which actually fixes the problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, the problem in my case is that I have a couple of hundred files that need this problem fixed, I don’t want to go inside each file and fix this as that would be extremely time-consuming. Is there a way to configure PHP 8 to ignore this and still proceed with the count function with these $_POST parameters? or some sort of search/replace regex that I can run on all files that replace count($_POST['some_parameter_name']) with count((array)$_POST['some_parameter_name']))? Honestly, I have no idea how I can fix this problem without manually going into each file, and this is the part where I need your help.

>Solution :

One temporary solution would be to define your own count() function. For instance:

function oldCount($input)
{
   return isset($input) && is_array($input) ? count($input) : 0;
}

This is just a quick example. You can use your (array) thing as well.

Now all you need to do is replace all the occurrences of count( in your code by oldCount(, and you’re done.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading