You can't convert that while
to a for
.
for
loops are used for incremental loops. while
loops are used to execute code until a condition is false
. While most for
loops can be easily converted to while
loops (for
loops are just a syntactical enhancements of while
loops), the opposite is not always possible.
Consider the following loop:
while($row = pg_fetch_row($result)) { }
This loop will execute until pg_fetch_row()
returns a falsy value.
Note: The proper syntax for such a loop would be:
while(($row = pg_fetch_row($result)) !== FALSE) { }
Unfortunately, the closest you can come to using a for
loop is the following:
for(; $row = pg_fetch_row($result) ;) {}
Which will behave exactly the same as the while
loop anyway.
Note: Again, the proper syntax for such a loop would be:
for(; ($row = pg_fetch_row($result)) !== FALSE ;) { }
I think you should go back in your code and find exactly the cause of your problem instead of blaming the use of the while
loop.
pg_fetch_row()
returns an array of columns, so you cannot use count()
on it.
The closest you can come to using a for
loop would be using pg_num_rows
as such:
for($i = 0; $i < pg_num_rows($result); $i++) {
$row = pg_fetch_row($result);
}
But personally I find that unnecessarily verbose and open to more problems.