PHP needs a while-else statement

I think PHP ought to have a while-else statement. There is, of course, a while statement and an if-else statement, but a while() else statement would be perfect for returning a bunch of rows from a MySQL database:

<?php

$q = mysql_query("SELECT name FROM people WHERE age >= 21");
while (
$person = mysql_fetch_assoc($q))
{
    echo
"$person[name] is at least 21 years old.";
}
else
{
    echo
"No one 21 or older was found in the database!";
}

?>

This hypothetical code queries the database for everyone age 21 or older, looping through all the results. If no results were found, it very conveniently says so. Because there is no while-else statement, the programmer has to nest the the while() loop inside an if() statement. A while-else statement would be much cleaner.

This entry was posted in Main. Bookmark the permalink.

7 Responses to PHP needs a while-else statement

  1. Alex Kadis says:
    Interesting thought, I am inclined to agree with you, however I do not know what would go into making something like this happen, and I have no idea if it is even feasible. Perhaps someone with more knowledge on the subject will chime in.
  2. Gustavo Narea says:
    +1.

    Any PHP developer there?

  3. PHP doesn’t support that, but Smarty does.

    I normally use
    foreach / else to display tables.

  4. taaniel says:
    agreed, but alternative way is use one variable and if after while, for example

    $q = mysql_query(‘SELECT * FROM tbl’);
    $n = 0;
    while($r = mysql_fetch_assoc($q))
    {
    // do something
    ++$n
    }
    if(0 == $n)
    {
    // no rows found
    }

  5. Pingback: Richard K Miller dot coooooooooom » PHP 5 and Beyond

  6. redcore says:
    I definitely agree. In fact, I was just trying to just that and upon that not working I googled it and realized it doesn’t exist. It’s a common sense statement, if you ask me (hence why I tried doing it). I reckon a post on php.net’s forum would be a good way of seeing why this cannot be done and if it can, give it some thought and perhaps enough traction to be implimented.
  7. Jacques says:
    I wholeheartedly agree, here’s something that I’ve considered using that represents the while-else. The only problem is if you change the list=fetch line, you have to do it twice.

    if (list($a,$b) = mysql_fetch_row($result)) {
    do {
    process($a,$b);
    } while (list($a,$b) = mysql_fetch_row($result));
    } else {
    print “No results returned”;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>