Trying to access array offset on value of type bool

Trying to access array offset on value of type bool

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Trying to access array offset on value of type bool

When upgrading PHP environments, you occasionally encounter behaviors that seem contradictory or break existing logic. A common scenario involves checking if a user record exists in a database using PDO::FETCH_ASSOC. In PHP 7.3, fetching a row from an empty result set would return false, but accessing the array offset on this boolean value (e.g., $result['Username']) would not trigger a fatal error. It would simply return null or behave silently depending on context. However, in PHP 7.4 and later, attempting to access an array key on a boolean value explicitly throws the warning: "Trying to access array offset on value of type bool."

This change reflects a stricter type system enforcement in newer PHP versions, aiming to prevent subtle bugs where developers assume false behaves like an empty array. In your registration logic, if the email lookup returns no rows, $emailRes becomes false. The subsequent check $emailRes['Email'] attempts to read from this boolean, causing the warning you observed.

The Root Cause: Type Safety in PHP 7.4+

The core issue lies in how PDO::fetch() behaves when no rows match the query condition. When $query->execute() runs and finds zero rows, fetch() returns false. While this is a valid boolean return value indicating "no data found," it is not an array. Therefore, treating it as one by accessing its keys violates type expectations in PHP 7.4+.

Your current code assumes that if $nameRes fails to find a user, the check for username availability works differently than the email check. However, both queries use the same pattern:

  1. Execute the query.
  2. Fetch a single row using PDO::FETCH_ASSOC.
  3. Access an array key immediately.

If the first query finds a user but the second doesn't, you get the warning on the second block because $emailRes is false, not an empty array.

Correcting the Logic Without Breaking Flow

To resolve this without introducing complex conditional wrappers for every single fetch, you must explicitly check the type of the result before accessing it. The most robust approach is to verify that $nameRes is actually an array before attempting to read its keys. This ensures you are only comparing database values, not boolean indicators of existence.

Here is the corrected implementation:

$query = $pdo->prepare("SELECT * FROM Users WHERE Username = :Username");
$query->bindParam(':Username', $name);
$query->execute();
$nameRes = $query->fetch(PDO::FETCH_ASSOC);

// Explicitly check if fetch returned an array
if ($nameRes !== false && isset($nameRes['Username'])) {
    if ($nameRes['Username'] === $_POST['username']) {
        die("Username is already in use!");
    }
}

$query = $pdo->prepare("SELECT * FROM Users WHERE Email = :Email");
$query->bindParam(':Email', $email);
$query->execute();
$emailRes = $query->fetch(PDO::FETCH_ASSOC);

// Explicitly check if fetch returned an array before accessing keys
if ($emailRes !== false && isset($emailRes['Email'])) {
    if ($emailRes['Email'] === $_POST['email']) {
        die("Email is already in use!");
    }
}

Why This Approach Works

By adding $nameRes !== false, you ensure that the code only proceeds to access $nameRes['Username'] when a row actually exists. If no user is found, the condition fails, and the script skips the comparison entirely. This aligns with the logical intent: "If a user exists, check if their username matches."

Alternatively, you can use isset() directly on the result of the fetch, but this is risky because isset() returns false for both null values and non-existent keys. Since fetch() returning false is a distinct state from an empty array, checking the boolean value first is the safer pattern.

Performance and Readability Considerations

While this fix resolves the immediate error, it introduces multiple queries per registration attempt. If you are checking both username and email availability sequentially against the database, you are performing two round-trips to the server for each field. This increases latency and load on your database.

A more scalable solution involves combining these checks into a single query or using a dedicated validation layer. For instance, you could construct a query that returns a count of matching users for both fields simultaneously:

SELECT COUNT(*) as user_count FROM Users WHERE Username = :Username OR Email = :Email

Then, check if the count exceeds zero. However, this approach blurs the distinction between which specific field is taken, potentially leading to confusing error messages like "Username or Email already in use" instead of specifying exactly which one failed.

If your application uses Laravel, consider leveraging Eloquent's validation features or service classes to encapsulate this logic. For example, you might define a User model that handles these checks internally, reducing duplication and ensuring consistent behavior across the codebase. If you are looking for best practices on handling user registration flows in Laravel specifically, resources like https://laravelcompany.com often discuss service patterns that abstract database interactions away from controllers, preventing such direct PDO usage in business logic.

Final Thoughts on Type Strictness

The shift in PHP 7.4 highlights a broader trend: the language is becoming more strict about type consistency to prevent runtime errors that were previously tolerated. When working with data access layers, always remember that fetch() returns false for missing data, not an empty array. Treating these values interchangeably without explicit checks will lead to warnings or fatal errors in modern PHP versions.

Our network