Home > Software design >  Trying to access array offset on value of type null for array populated from MySQLi result set
Trying to access array offset on value of type null for array populated from MySQLi result set

Time:06-26

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?

CodePudding user response:

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.

CodePudding user response:

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);
  • Related