Zan Kravitz
Zan Kravitz

Reputation: 41

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

Upvotes: 3

Views: 53

Answers (1)

Rizier123
Rizier123

Reputation: 59681

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.

Upvotes: 2

Related Questions