count() throws a TypeError on null or a non-array in PHP 8
Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null givenShort answer
Since PHP 8.0.0, count() accepts only an array or an object that implements Countable and throws a TypeError for anything else. PHP 7 gave 0 for null and 1 for other values. Find which variable is null or not an array, fix where it gets its value, and guard the call with is_countable() when the input may vary.
Fix it fast
1Find out which cause you have
Dump the type of the value right before the failing line. The type in the error message already names it, but this shows where it went wrong.
var_dump($rows); // add just before the count() call php -v2Match what you see, then jump to its fix
- 1
Countable|array, null givenThe variable is null because a lookup returned nothingFix - 2
Countable|array, bool given (or string, int)A function returned false or a scalar instead of an arrayFix - 3
must be of type Countable|array, stdClass given (or another class name)A plain object that does not implement CountableFix
- 1
What does the error look like?
Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null givencount(): Argument #1 ($var) must be of type Countable|array, bool given
Cause 1 of 3
The variable is null because a lookup returned nothing
1Check
Trace where the variable is set. A missing array key read with ??, an unset variable, an uninitialised property or a function that returns null on no result all end up here. PHP 7 quietly returned 0 for null; PHP 8.0.0 throws.
var_dump($rows, gettype($rows));2Fix
Fix the source so it returns an empty array when there is no data. Where that is not possible, default it at the call site.
$total = count($rows ?? []);
// or, when the type may be anything
$total = is_countable($rows) ? count($rows) : 0;3Verify
Run the same request with no data and confirm the page or script finishes with 0.
php -r '$rows = null; echo is_countable($rows) ? count($rows) : 0;'Confirmed by php.net
Cause 2 of 3
A function returned false or a scalar instead of an array
1Check
Many functions return false on failure, and the manual says a call like count(false) now throws. Check the return value of the call that fills the variable.
var_dump(gettype($rows)); // bool means the producing call failed2Fix
Check the return value strictly before using it, and handle the failure on its own path.
if ($rows === false) {
throw new RuntimeException('Query failed');
}
$total = count($rows);3Verify
Force the failing case once (for example a bad query) and confirm the exception appears instead of a TypeError.
php -l src/report.phpConfirmed by php.net
Cause 3 of 3
A plain object that does not implement Countable
1Check
count() works on an object only if its class implements the Countable interface. A stdClass from json_decode() or a result object does not.
var_dump($result instanceof Countable);2Fix
Count the array you really mean, or implement Countable on your own class. The manual's example adds a count(): int method.
class Basket implements Countable
{
private array $items = [];
public function count(): int
{
return count($this->items);
}
}3Verify
count($basket) now returns an integer without error.
php -r 'class B implements Countable { function count(): int { return 2; } } echo count(new B);'Confirmed by php.net
How do I stop it coming back?
- Return an empty array instead of null from functions that return lists.
- Declare array types on parameters and properties so a null is caught where it starts.
- Use is_countable() at boundaries where the input comes from outside (JSON, forms, database calls).
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix