Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable|array, null given in

Tags:

php

count

The code was working perfectly until when I installed XAMPP 8 (PHP 8).

$size = count($_POST['adm_num']);

But now it's throwing "Argument #1 ($var) must be of type Countable|array, null given" error.

like image 496
Asgwani Avatar asked Sep 06 '25 09:09

Asgwani


2 Answers

In case the array may not exist, you can check its existence and type before counting, and then either set a default value or return an error, if array is expected

if (isset($_POST['adm_num']) && is_countable($aa)) {
    $size = count($_POST['adm_num']);
} else {
    $size = 0;
    // http_response_code(400);
    // die("adm_num must be present and be of type array");
}

In case the array must be defined at this point, this error means that something is broken in your code and you have to debug it, checking the source of this array.

like image 104
mahdi marjani moghadam Avatar answered Sep 07 '25 22:09

mahdi marjani moghadam


Starting from PHP8.0, using proper type is obligatory for the most function parameters. As a simple solution you may cast a variable to array before counting.

count((array)$XYZVariable);

try this code

$size = count((array)$_POST['adm_num']));

However it may cause unexpected behavior and it's recommended to validate the input value instead, by checking its type and returning an error if validation fails.

like image 41
Sumit patel Avatar answered Sep 07 '25 23:09

Sumit patel