Edit report at https://bugs.php.net/bug.php?id=65181&edit=1

 ID:                 65181
 Updated by:         a...@php.net
 Reported by:        ducciogrun at gmail dot com
 Summary:            Merging the "do {} while(cond)" and "while(cond){}"
                     structures
-Status:             Open
+Status:             Feedback
 Type:               Feature/Change Request
 Package:            *General Issues
 Operating System:   Any
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

What about while (false !== ($row = $result->fetch_assoc())); ?


Previous Comments:
------------------------------------------------------------------------
[2013-07-02 08:35:45] ducciogrun at gmail dot com

Description:
------------
An example directly from the Php documentation 
(http://php.net/manual/en/function.mysql-fetch-assoc.php):

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

It's old, it's prone to errors and my IDE (Zend Studio) always reports a 
"assignment in condition" warning. And many times thw work to be done on the 
first iteration is a lot more complicated than that.

One solution is to duplicate code:

    /* fetch associative array */
    $row = $result->fetch_assoc();
    while ($row) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
        $row = $result->fetch_assoc(); //Duplicate code
    }


But it is not the best, both to read and to mantain.

An elegant solution could be the following structure:

    /* fetch associative array */
    do {
        $row = $result->fetch_assoc();
    } while ($row) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

Merging "do { } while(cond)" and "while(cond){}" would come handy anytime there 
is code that should be run at the first iteration and at any subsequent 
iteration, before the condition is checked.

The same purpose could be achieved by 

    /* fetch associative array */
    do {
        $row = $result->fetch_assoc();
        if($row) {
            printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
        }
    } while ($row);

But it adds a level of nesting and it forces php to check twice the condition.



------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=65181&edit=1

Reply via email to