PHP 7.2 - Warning: count(): Parameter must be an array or an object that implements Countable
Upgrading from PHP 5.6 to 7.2 often reveals latent bugs in legacy code, particularly around type checking. One of the most common stumbling blocks is the count() function warning: "Parameter must be an array or an object that implements Countable." This error frequently surfaces when developers attempt to check the existence of a row returned from a database query using $conn->fetch().
Consider the scenario where you are upgrading an authentication script. You might have code that looks like this:
$results = $conn->fetch(PDO::FETCH_ASSOC);
if (count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
// Login successful
}
In PHP 5.6, this would execute without issue because the language was more lenient regarding type hints on return values of functions like fetch(). However, PHP 7.2 enforces stricter standards. The method PDOStatement::fetch() does not return an array; it returns either a single associative array (representing one row) or false if no rows are found or the fetch fails.
The root cause of the warning lies in how count() interacts with these specific return types. When the query yields no results, $results is set to false. You cannot pass false to count(), which strictly requires an array or an object implementing the Countable interface. Attempting to do so triggers the runtime warning because false is a boolean value, not a collection.
The solution is straightforward but requires a shift in logic compared to older PHP versions. Instead of counting the rows returned by a single fetch operation, you should check if the result is actually an array before attempting any further operations. The most idiomatic way to handle this in modern PHP is to use is_array().
Here is the corrected implementation for your login logic:
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$records = $conn->prepare('SELECT id, username, password FROM users WHERE username = :username');
$records->bindParam(':username', $_POST['username']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if ($results !== false && password_verify($_POST['password'], $results['password'])) {
$_SESSION['user_id'] = $results['id'];
header("Location: /");
} else {
// Handle failure: either no user found or password mismatch
$message = 'Sorry, those credentials do not match';
}
}
By replacing count($results) > 0 with $results !== false, you align your code with the actual contract of the PDOStatement::fetch() method. This approach is cleaner and more performant as well. Checking for false avoids unnecessary function calls and directly addresses the nullability defined by the PDO API.
Another potential pitfall to watch out for involves the database connection itself. If the query fails due to a syntax error or a missing table, $records->execute() might throw an exception depending on your error mode settings (e.g., PDO::ERRMODE_EXCEPTION vs PDO::ERRMODE_SILENT). In strict environments, you should ensure that exceptions are caught or configured appropriately so that $results is not inadvertently treated as a valid object when it represents a failed execution state.
If you are working within the Laravel ecosystem, this specific pattern of manually checking database results often resolves itself through the framework's ORM abstractions like Eloquent. However, even in vanilla PHP applications using PDO, understanding the return types of your data access layer is essential for writing robust code that survives version upgrades.
For developers looking to manage these upgrades smoothly while maintaining high security standards, resources such as https://laravelcompany.com offer insights into modernizing legacy PHP stacks without sacrificing performance or introducing new vulnerabilities. The transition from lenient type coercion in 5.6 to strict typing in 7.x is a necessary step toward more predictable software behavior, and addressing these warnings immediately prevents subtle logic errors that could lead to security flaws or unexpected application crashes.
