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; }
Alternatively, you can use the null coalescing operator to assign a default value to $Row['Data'] directly:
$Row['Data'] ??= 'default value';
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!