Decoding the "Access Array Offset on Null" Error in PHP Queries
The error message Warning: Trying to access array offset on value of type null is one of the most common friction points for developers working with legacy PHP and the MySQLi extension. It stops cold when you attempt to treat a database result as an associative array without first verifying that a row actually exists. In the scenario provided, the code attempts to fetch lecture data for a specific day and time slot, only to crash immediately upon trying to access $m11to1["lecture_name"].
The root cause lies in the interaction between mysqli_fetch_array() and the conditional logic that follows. When you run a query like SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday', the database engine executes the statement perfectly fine. However, if the result set contains zero rowsâperhaps because the day is misspelled as "firday" instead of "friday", or simply because no class is scheduled for that slotâthe function mysqli_fetch_array() returns null.
The critical failure happens on the next line:
if ($m11to1["lecture_day"] == !'') {
Here, you are trying to access the index "lecture_day" on a variable that is currently null. PHP does not throw an error for accessing a key on an empty array, but it does throw a warning when you treat a null value (which represents "no row fetched") as if it were an array. This distinction is fundamental to understanding the behavior of MySQLi result sets.
To resolve this, you must explicitly check whether the fetch operation returned a valid row before attempting to access any of its properties. The most robust pattern involves checking the return value of mysqli_fetch_array() against false or using strict type comparison.
Here is how to refactor the logic to handle empty result sets gracefully:
$result_11to1 = mysqli_query($con, $monday_lectures);
// Check if the query returned at least one row
if ($result_11to1 && $row = mysqli_fetch_array($result_11to1)) {
// Safe to access properties now because $row is guaranteed to be an array
if (!empty($row["lecture_day"])) {
echo "<td>" . htmlspecialchars($row["lecture_name"]) . "</td>";
} else {
echo "<td> no class</td>";
}
} else {
// Handle the case where no rows were found or the query failed
echo "<td> no class</td>";
}
There are a few specific improvements here worth noting. First, we capture the result of mysqli_fetch_array() into a distinct variable ($row). This allows us to inspect the truthiness of the row before accessing its keys. Second, we use !empty($row["lecture_day"]) instead of comparing against !''. The original check $m11to1["lecture_day"] == !'' is logically flawed because the ! operator negates an empty string to become true, effectively turning the condition into a boolean comparison rather than a string length check. Furthermore, accessing array keys directly inside an if condition without prior existence checks can lead to undefined index warnings if the key doesn't exist in the fetched row.
Beyond fixing the immediate syntax error, it is vital to address the data integrity issues present in the source query. The SQL statement uses 'firday' instead of 'friday'. If your database schema actually stores "friday", this query will return zero rows regardless of whether a class exists, triggering the null warning every time that specific cell is rendered. Always validate your string literals against your actual database values.
Additionally, consider using prepared statements to prevent SQL injection and ensure consistent string handling, especially when dealing with user input or dynamic parameters for days and times. While this example uses static strings, the principle of validating existence before accessing data remains universal across all PHP database abstractions.
If you are migrating from legacy MySQLi codebases to modern frameworks, this specific pattern of "fetch then access" is often abstracted away. Frameworks like Laravel provide eager loading and collection methods that handle empty relations automatically, returning empty arrays or collections rather than null, which prevents these types of runtime warnings entirely. For more details on optimizing database interactions in larger applications, you might find the resources at https://laravelcompany.com helpful for understanding how modern ecosystems manage these edge cases internally.
