How to Fix "Trying to Access Array Offset on Value of Type Null" in PHP 7.4
In PHP 7.4, an error occurs when attempting to access an array key of a null value. This is a departure from previous PHP versions that would often ignore such errors.
Root Cause:
The error highlighted in the question originates from a line that attempts to count the elements in an array key ('char_data') of the variable $cOTLdata. The problem lies in the fact that $cOTLdata is null, resulting in the error message "Trying to access array offset on value of type null."
Solution:
To resolve this issue, you can employ one of the following strategies:
1. Use is_null():
This function allows you to explicitly check if the variable $cOTLdata is null:
$len = is_null($cOTLdata) ? 0 : count($cOTLdata['char_data']);
If $cOTLdata is null, it returns 0; otherwise, it counts the elements in $cOTLdata['char_data'].
2. Use isset():
Alternatively, you can use isset() to check if both $cOTLdata and $cOTLdata['char_data'] exist simultaneously:
$len = !isset($cOTLdata['char_data']) ? 0 : count($cOTLdata['char_data']);
This line ensures that $len is set to 0 if either $cOTLdata or $cOTLdata['char_data'] is not set, and returns the count of $cOTLdata['char_data'] if both variables are set.
The above is the detailed content of How to Resolve the PHP 7.4 Error \'Trying to Access Array Offset on Value of Type Null\'?. For more information, please follow other related articles on the PHP Chinese website!