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

Viewed 49326

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

if(isset($_POST["submit"])){
    @$subject = $_POST['subject'];
    @$term = $_POST['term'];
    @$session = $_POST['session'];
    @$size = count($_POST['adm_num']);
    @$size = count($_POST['ca1']);
    @$size = count($_POST['ca2']);
    @$size = count($_POST['ca3']);

    $i = 0;
    while ($i < $size) {
        $ca1= $_POST['ca1'][$i];
        $ca2= $_POST['ca2'][$i];
        $ca3= $_POST['ca3'][$i];
        $adm_num = $_POST['adm_num'][$i];
    }
}
6 Answers

You must defined variable with array() before use it. or

if (is_countable($aa) && count($aa) > 0) :

On PHP8.0 compulsory types are define on Count.

count((array)$XYZVariable);

try This Code

if(isset($_POST["submit"])){
    @$subject = $_POST['subject'];
    @$term = $_POST['term'];
    @$session = $_POST['session'];
    @$size = count((array)$_POST['adm_num']));
    @$size = count((array)$_POST['ca1']));
    @$size = count((array)$_POST['ca2']));
    @$size = count((array)$_POST['ca3']));

    $i = 0;
    while ($i < $size) {
        $ca1= $_POST['ca1'][$i];
        $ca2= $_POST['ca2'][$i];
        $ca3= $_POST['ca3'][$i];
        $adm_num = $_POST['adm_num'][$i];
    }
}

Easy Fix ..

$ab = is_array($aa) ? count($aa) : 0 ;

Thanks

@$size = count($_POST['ca1']); 

in PHP 8 will not work you have to do it like that

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

and do this for the rest of it

Quoting from the official php docs for count():

Counts all elements in an array, or something in an object.

The error you're getting is pretty obvious. One of these four variables($_POST['adm_num'], $_POST['ca1'], $_POST['ca2'], $_POST['ca3']) is not an array or maybe more.

You can find out about the type of a variable using gettype(). It'll tell you that which variable does not contains an array. You can than change it to array.

P.s: You're overriding your $size variable three times. Why is that?

In the doc it say :

Return Values Returns the number of elements in value. When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if value is null, 0 will be returned.

It look like it a bug ?!?

Related