Home > Backend Development > PHP Tutorial > Why Does PHP 7.4 Throw \'Trying to Access Array Offset on Value of Type Bool\'?

Why Does PHP 7.4 Throw \'Trying to Access Array Offset on Value of Type Bool\'?

Barbara Streisand
Release: 2024-11-27 01:46:10
Original
779 people have browsed it

Why Does PHP 7.4 Throw

Understanding the Error: Array Offset Access on Boolean

PHP 7.4 introduced a change in strict type checking, leading to the error "Trying to access array offset on value of type bool." This error occurs when trying to access an element of an array using the array syntax (square brackets) on a value that is of type boolean.

The PHP 7.4 Fix

In the example provided, the error is thrown because $Row['Data'] returns a boolean value when the query result is empty. To fix this, you can use the null coalescing operator (??) to check if $Row['Data'] is null and assign it a default value if it is. This ensures that you can always access the array element without encountering the error.

Here's an updated version of the code using the null coalescing operator:

public static function read($id)
{
    $Row = MySQL::query("SELECT `Data` FROM `cb_sessions` WHERE `SessionID` = '$id'", TRUE);

    $session_data = $Row['Data'] ?? '';

    return $session_data;
}
Copy after login

Alternatively, you can use the null coalescing operator to assign a default value to $Row['Data'] directly:

$Row['Data'] ??= 'default value';
Copy after login

This will set $Row['Data'] to 'default value' if it's null, and then return its value as usual. Both methods effectively prevent the error by ensuring that $Row['Data'] is always evaluated to a valid array offset value.

The above is the detailed content of Why Does PHP 7.4 Throw \'Trying to Access Array Offset on Value of Type Bool\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template