I finally got around to updating my PHP installation from 7.2 to 7.4 (planning to update directly to the current version, but doing it in steps), and when I run the existing script I get a strange error:
Message: Attempt to access array offset on value of type null
The line that appears simply populates an array from a simple mysql result set.
for($i = 0; $resultArray[$i] = mysqli_fetch_row($result)[0]; $i++) ;
The script still runs fine, but I just don't like any errors. I'm confused as to why this is going wrong and have searched for hours to no avail. Why does this error occur? Is there any way to perform the same operation without errors?
P粉0769873862024-01-03 16:51:35
According to the documentation, mysqli_fetch_row
will return null
once the end of the result set is reached.
You can use a foreach
loop. I don't recommend it, but it's a possible solution.
foreach ($result->fetch_all() as [0 => $resultArray[]]); // no body needed
You really don't need to use this weird device. You can use array_column() for simpler operations.
$resultArray = array_column($result->fetch_all(), 0);
P粉6814003072024-01-03 14:58:49
mysqli_fetch_row
will return null
at some point (according to the documentation, it always does this when it runs out of rows to retrieve). But you didn't check it before trying to read its 0th index, so you get the error.
Many people use this style to retrieve rows:
while ($row = mysqli_fetch_row($result)) { $resultArray[] = $row[0]; }
This will avoid such problems. This is also how you often see it done in examples and documentation.