Fixing “count(): Parameter must be an array or an object that implements Countable” Error in CodeIgniter 3
Fixing “count(): Parameter must be an array or an object that implements Countable” Error in CodeIgniter 3
If you are working with CodeIgniter 3 and encounter the following error:
count(): Parameter must be an array or an object that implements Countable
This issue occurs when running your application on PHP 7.4 or later. In PHP 7.2 and older versions, passing NULL
to count()
was allowed without any errors. However, in PHP 7.3 and later, count()
only accepts arrays or objects that implement the Countable
interface.
Why This Error Occurs
If the variable being passed to count()
is NULL
, PHP throws this error because NULL
is neither an array nor an object that implements Countable
.Consider the following example in your controllers/Page.php
:if (count($this->data['DataList']) > 0) {
If
// Code execution
}$this->data['DataList']
is NULL
, this will trigger the error.
Solution
To fix this error, always check if the variable is set and is an array before using count()
. Modify your code as follows:if (isset($this->data['DataList']) && is_array($this->data['DataList']) && count($this->data['DataList']) > 0) {
Alternatively, you can use the null coalescing operator (
// Code execution
}??
) introduced in PHP 7.0:if (count($this->data['DataList'] ?? []) > 0) {
ConclusionBy ensuring that the variable is properly checked before passing it to
// Code execution
}count()
, you can avoid this error and ensure your CodeIgniter 3 application runs smoothly on PHP 7.4 and later. Always follow best practices when handling arrays and objects to maintain compatibility across different PHP versions.