1

I finally got round to updating my PHP install to 7.4 from 7.2 (Planning on going right to current but doing in steps) and a curious error appeared when I was running an existing script:

Message: Trying to access array offset on value of type null

The line that this appears on is simply to populate an array from a simple mysql result set.

for($i = 0; $resultArray[$i] = mysqli_fetch_row($result)[0]; $i++) ;

The script still continues fine but I just don't like any errors. I'm scratching my head why this has errored and searched for a few hours to no avail. Why is this erroring and is there a way to do the same thing with no error?

2
  • The way to avoid such a situation is of course to either a) write your code in such a way that the variable can never be null, or b) write code check that it isn't null before trying to access an index within it. Commented Jun 25, 2022 at 16:57
  • 1
    You could rewrite as for($i = 0; $resultArray[$i] = mysqli_fetch_row($result)[0] ?? null; $i++);. This will work, because when mysql_fetch_row() has no more data, it will return null and is also the break condition. Commented Jun 25, 2022 at 17:08

2 Answers 2

0

mysqli_fetch_row will return null at some point (as it always does when it runs out of rows to retrieve, as per the documentation). But you're not checking that before trying to read its 0th index, hence the error.

Many people retrieve rows using this kind of style:

while ($row = mysqli_fetch_row($result)) { 
  $resultArray[] = $row[0]; 
}

which will avoid this sort of problem. That's the way you'll often see it done in examples and documentation, too.

Sign up to request clarification or add additional context in comments.

Comments

-1

As per the documentation mysqli_fetch_row will return null once it reaches the end of the result set.

You can use a foreach loop. I wouldn't recommend it, but it's a possible solution.

foreach ($result->fetch_all() as [0 => $resultArray[]]); // no body needed

You don't really need to use this strange contraption. You can do it even simpler using array_column().

$resultArray = array_column($result->fetch_all(), 0);

2 Comments

I'm interested in what benefit would this solution have over the accepted 'while' solution?
@JamesMatthews It's much cleaner, isn't it? It's only 1 line vs 4. No loop is necessary with array_column. It's faster than a loop, not that it would make any difference in real life. The mysqli_result object doesn't have to be rewound if you want to use it again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.