To convert PHP's while loop to a for -loop

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

Upvotes: 1

Views: 1803

Answers (3)

Andrew Moore
Andrew Moore

Reputation: 95424

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.

Upvotes: 9

outis
outis

Reputation: 77420

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.

Upvotes: 5

Daniel A. White
Daniel A. White

Reputation: 190976

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.

Upvotes: 1

Related Questions