Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count() gives me wrong output after while loop

I'm fetching data from my database and count() gives me a wrong output after fetching the data in a while loop. Why?

Output is:

Line: 1 
Line: 2
Count after loop: 3

Code:

while($line[] = mysqli_fetch_array($result)){
    echo 'Line: '.count($line);
}
echo 'Count after loop: '.count($line);
like image 230
Zan Kravitz Avatar asked Jun 11 '26 01:06

Zan Kravitz


1 Answers

This is because in the 3rd iteration mysqli_fetch_array() will return NULL, since there are no rows left, which you then add to the array.

On NULL which evaluates to FALSE the while loop will stop, but it gets added to the array. So you then have 3 elements, e.g.

Array ( 
    [0] => something
    [1] => something
    [2] => NULL
)

You can see this when you do: var_dump($line);. Also to solve this now, you can simply put the code in the while loop to add the element, e.g.

while($row = mysqli_fetch_array($result)){
    $line[] = $row;
    echo 'Line: '.count($line);
}
echo 'Count after loop: '.count($line);

So with this you won't add $row to $line if $row holds NULL.

like image 195
Rizier123 Avatar answered Jun 13 '26 17:06

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!