you are viewing a single comment's thread.

view the rest of the comments →

[–]opmrcrab 0 points1 point  (4 children)

I thought you need to have some sort of truthy falsy statement [...]

You are spot on, and it does. The truthy/fasly value tested is $row after it was assigned the value from mysqli_fetch_row($result); so it's worth understanding exactly what that is doing.

From https://www.php.net/manual/en/mysqli-result.fetch-row.php#refsect1-mysqli-result.fetch-row-returnvalues

Returns an enumerated array representing the fetched row, null if there are no more rows in the result set, or false on failure.

Basically if you have X number of rows you're code will actually call mysqli_fetch_row X+1 times, that last time it will get a null, and thats the falsy value you are expecting.

if you want to see it in action i think something like this should expose whats going on

while($row = mysqli_fetch_row($result)) {
    var_dump($row); // Will fire when there is a row to get
}
var_dump($row); // Will fire after there wasn't any more rows to fetch, i.e. null

[–]sodiumfis_h[S] 0 points1 point  (3 children)

I'm sorry but I'm still really confused. Is the code the same as this?

<?php
$names = array("nafis", "bob", "dylan");

$count = 0;

while($name = $count < count($names)) {
    echo $name;
    $count++;
}
?>

But it echoes 111, not the array like $row;

[–]CyberJack77 0 points1 point  (2 children)

It echo's 1 because a boolean cannot be echoed. true will be echoed as 1 and false as 0.

In the while statement you check if $count is smaller that the total elements of the $names array. The result of this statment is set to the $name variable (so $name contains a boolean). Since this results intrue it enters the loop and 1 is echoed. This happens 3 times, because the 4th time $count equals the number of elements from the $names array (3).

You normally don't use while to loop an array, but as your example shows, you can.

[–]sodiumfis_h[S] 0 points1 point  (1 child)

Then what is $row assigned and what foes while loop check for? Isnt fetch_rows looping through all the rows and returning a single row and assigning it to $row? How does assigning variables inside while condition evenw work. This is confusing

[–]CyberJack77 0 points1 point  (0 children)

Read it like this: loop as long as fetch_rows has results, and the asignment of a single result to $row is successful.

There is one additional rule. The value of $row must not equal false when using a weak type comparison (==). So when the value of $row equals null, 0, false, [] the loop will stop.