Home >Backend Development >PHP Tutorial >Why am I getting the 'Trying to access array offset on value of type null' error in PHP?
Trying to Access Array Offset on Value of Type Null Error in PHP: Addressing the Issue
The "Trying to access array offset on value of type null" error in PHP arises when an attempt is made to access an array element that does not exist. This error typically occurs when a database query results in an empty array or a null value.
Understanding the Error
In PHP, database fetching functions return either null or an empty array when there are no matching records or when the result set has been exhausted. Consequently, it is crucial to check for the existence of data before accessing array elements.
Resolving the Issue
To resolve this error, employ one of the following techniques:
1. Explicitly Checking for Data Existence:
$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'"; $result_11to1 = mysqli_query($con, $monday_lectures); $m11to1 = mysqli_fetch_array($result_11to1); if ($m11to1 && $m11to1["lecture_day"] !== '') { echo "<td>".$m11to1["lecture_name"]."</td>"; } else { echo "<td> no class</td>"; }
2. Using Null Coalescing Operator:
$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'"; $result_11to1 = mysqli_query($con, $monday_lectures); $m11to1 = mysqli_fetch_array($result_11to1); $lecture = $m11to1["lecture_day"] ?? null;
This approach allows you to specify a default value for the array element if it does not exist.
The above is the detailed content of Why am I getting the 'Trying to access array offset on value of type null' error in PHP?. For more information, please follow other related articles on the PHP Chinese website!