Back in time, many PHP programmers used to call PHP’s count() function with different kind of parameters, like arrays, empty strings or even null.

For example, in PHP 5.6.20 or newer PHP 7.1.0, this will run without any thrown Warning:

$data = null;
if(count($data) > 1) {
   echo "We have data";
} else {
   echo "We don't have data";
}

Starting with PHP 7.2, this produces a Warning:

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

But from PHP 8.0, this produces a Fatal Error:

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

Using empty function instead of count, on null vars

While using count was a bad practice even in the past, it is now a must to avoid it in such cases. It is recommended to use empty function to detect if a variable is not an empty array, nor null.

So, the code above becomes:

$data = null;
if(!empty($data)) {
   echo "We have data";
} else {
   echo "We don't have data";
}

You should note that the following values evaluates to empty:

0
0.0
"0"
""
null
false
array()
Last modified: May 8, 2021

Author