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

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];
    }
}


Solution 1:[1]

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

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

Solution 2:[2]

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];
    }
}

Solution 3:[3]

Easy Fix ..

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

Thanks

Solution 4:[4]

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?

Solution 5:[5]

@$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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mahdi marjani moghadam
Solution 2
Solution 3
Solution 4 Saud
Solution 5 Peter Csala