views:

286

answers:

3

How can you convert the following while loop to a for -loop in PHP?

while( $row2 = pg_fetch_row( $result_tags )

While -loops are a source of errors for me. I see the while -loop as follows.

for ( $i = 0 ; $i < count(pg_fetch_row( $result_tags )) ; $i++ )
A: 

Why do you want to do this? The better way is to declare/instantiate $i = 0 and then increment it at the end of the while loop.

Daniel A. White
+4  A: 

Going in the other direction, a for loop:

for (init; test; incr) {body;}

is equivalent to:

init;
while (test) {
    body;
    incr;
}

That is, a for loop is a special kind of while loop. Personally, I don't see how converting the while loop you give to a for loop will reduce errors.

outis
Thanks for showing this.
Daniel A. White
+8  A: 

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.

Andrew Moore
+1. This answer could use an explanation for the "!== FALSE" test, namely that an empty array will be type juggled to a FALSE and the loop will exit, even though `pg_fetch_row(...)` returned a row. Of course, if the rows have no columns, you might want to skip the loop. Also, the "!== FALSE" test is a matter of semantics, not syntax.
outis
Yes... but you can't say "the proper semantics"... That's why I said syntax.
Andrew Moore