php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #26411 while {} else {}
Submitted: 2003-11-25 12:28 UTC Modified: 2014-10-12 14:24 UTC
Votes:130
Avg. Score:4.4 ± 1.0
Reproduced:109 of 114 (95.6%)
Same Version:75 (68.8%)
Same OS:69 (63.3%)
From: php at bellytime dot com Assigned:
Status: Wont fix Package: Scripting Engine problem
PHP Version: * OS: *
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: php at bellytime dot com
New email:
PHP Version: OS:

 

 [2003-11-25 12:28 UTC] php at bellytime dot com
Description:
------------
How about a while...else structure. Often we do 

if (!mysql_num_rows($result)) {
   print 'No results found';
}
while ($row = mysql_fetch_assoc($result)) {
   print 'Here is a result';
   ...
}

Wouldn't it be nicer to do a 

while ($row = mysql_fetch_assoc($result)) {
   print 'Here is a result';
   ...
} else {
   print 'No results found';
}



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-11-25 19:16 UTC] elmicha@php.net
Can you give a better example to support your request? Your example can easily be written as:

while ($row = mysql_fetch_assoc($result)) {
   print 'Here is a result';
   ...
} 

if (!row) {
   print 'No results found';
}

I don't think that this one test is so expensive that it makes it worth the trouble (and cost) to clutter up the language.
 [2003-11-26 17:21 UTC] helly@php.net
Read again. Your code would always print 'No results found' while the intended change wouldn't.
 [2003-11-29 08:59 UTC] elmicha@php.net
Yes, you're right, my code was wrong. Next try:

$found = false;
while ($row = mysql_fetch_assoc($result)) {
   $found = true;
   print 'Here is a result';
   ...
} 

if (!$found) {
   print 'No results found';
}


The proposed while/else syntax is indeed a bit more elegant.

 [2008-04-09 07:51 UTC] ois at oisnot dot com
try {
  foreach ($nullValue as $nothing) {
    echo 'valid input';
  } else {
    //suppress notice
    echo 'null value';
  }
  //or/and
} catch (ExceptionObjectNotIterator $e) {
  //object doesnt implement Iterator
  echo $e->getMessage();
}
 [2010-11-19 00:19 UTC] jani@php.net
-Package: Feature/Change Request +Package: Scripting Engine problem
 [2010-12-19 13:08 UTC] trefighter2334 at aol dot com
I'd love to see something like Python's while/else logic implemented in PHP.

This logical construct would allow developers to define blocks of code in else 
{} that'd run upon a natural exit from the while(){} loop caused by said loop's 
condition becoming FALSE; however, the else {} would be skipped over if the loop 
exits unnaturally -- a la through a break statement or because of an exception.

It is to die for on a semi-daily basis for me (in python)... but I'm not sure 
this is what the developers above (and their examples) have in mind or not.

Either implementation would prove useful to me.
 [2011-02-18 01:14 UTC] ijrbiz at gmail dot com
Highly agreed, this request would be very practical for improved coding structure and 
follows logical language syntax nicely.

function remove_items (&$arr, $needle) {
	while ($key = array_search($needle, $arr)) {
		unset( $arr[$key] );
	} else return false; // No items present
	return true; // Item(s) removed
}
 [2011-12-06 16:31 UTC] absimu at hotmail dot com
I agree. I think a while () else () will make things easier. I was researching and 
found out that it doesnt exist yet. 


while($row = mysqli_fetch_assoc($result)) { }

with al else I would fix it.. I am new in PHP,. I will try to find something to 
fix it. but if the while else is release in a new version that would be nice.
 [2012-01-25 12:16 UTC] hawkyhawk14 at gmail dot com
This is a great idea. I am currently needing something like this, but however got 
around it using flags and making the flag true in the while. It would be alot more 
convenient if there was an else!

Please add this feature!!!
 [2012-04-26 02:13 UTC] ma-martin at hotmail dot de
Hey, i was also looking for some while {} else {} feature...
but i think it could be difficult to implement such a function in php.
Because the else{} event would start after the while{}-loop ends -> everytime after the last result!
think about it!
 [2012-08-21 17:38 UTC] bensor987 at neuf dot fr
Why don't you go a little bit further ?

while ( $row = mysql_fetch_assoc( $result ) ){

} else for ( $i = 0; $i < $cpt; $i++ ) {

} else if ( $dude ) {

} else {

}
 [2012-08-22 05:56 UTC] laruence@php.net
-Status: Open +Status: Wont fix
 [2012-08-22 05:56 UTC] laruence@php.net
no such syntax in other languages.
 [2012-08-22 10:09 UTC] nikic@php.net
-Status: Wont fix +Status: Open
 [2012-08-22 10:09 UTC] nikic@php.net
Revert status change.
 [2012-08-22 10:29 UTC] hawkyhawk14 at gmail dot com
laruence@php.net
no such syntax in other languages.
---------------------------------

Python has it and some versions of BASIC have it aswell.
 [2012-08-22 10:44 UTC] nikic@php.net
Python has an "else" for loops, but it means something completely different.
 [2012-08-22 16:46 UTC] bensor987 at neuf dot fr
"no such syntax in other languages"....what do you mean ? PHP doesn't have the right innovate ? 

I see plenty of cases I would use this syntax. The "else"s would be triggered if there hasn't been any iteration in the loop. It means : less variables to use (so less memory usage), less code lines, etc... 

There are only advantages to this syntax (and it's pretty simple to understand, no KISS violation here). It's not because it isn't done by other languages that we shouldn't implement it.
 [2012-08-22 17:05 UTC] rasmus@php.net
It's not that simple. Loops are repeatedly evaluated conditions. It isn't clear 
whether adding an else clause would only apply to the first evaluation or also 
subsequent ones.
 [2012-08-22 17:36 UTC] bensor987 at neuf dot fr
I understand your opinion. You want to make the "else" keyword usable only when "false" is encountered, like in "if...else". I didn't think about this.

In that case, let's use another keyword, because this syntax is an excellent idea.

Why not this ? 

<?php
while ($row = mysql_fetch_assoc($result)) {
   print 'Here is a result';
   ...
} none {
   print 'No results found';
}
?>
 [2012-08-23 17:09 UTC] bensor987 at neuf dot fr
I would like to go further in that way : "iterated". "iterated" would be parsed if there has been at least 1 iteration in the loop.
<?php
...
// Usual Case
$array_raw = SomeClass::getAll( $dbconn );
$cnt_raw = count( $array_raw );

$arr_output = array();

for ( $i = 0; $i < $cnt_raw; $i++ ) {
	$arr_output[] = $array_raw[$i]->id . ' - ' . $array_raw[$i]->label;
}
if ( $cnt_raw > 0 ){
	echo some_function( $arr_output );
} else {
	echo 'Nothing to display';
}
...
?>

<?php
...
// Shorter, faster, lighter
$array_raw = SomeClass::getAll( $dbconn );
$cnt_raw = count( $array_raw );

$arr_output = array();

for ( $i = 0; $i < $cnt_raw; $i++ ) {
	$arr_output[] = $array_raw[$i]->id . ' - ' . $array_raw[$i]->label;
} iterated {
	echo some_function( $arr_output );
} none {
	echo 'Nothing to display';
}
...
?>
 [2013-02-04 09:28 UTC] kjarli at gmail dot com
I don't really see a problem why not to implement this
<?php

while(!true) {
  // do something
} else[if[...]] {
  // nothing to do
}


//Could internally be translated to:

$looped = false;
while(!true) { 
  $looped = true;
  // do something
}

if(!$looped) {
  // nothing to do
}

?>
 [2013-02-04 19:56 UTC] bensor987 at neuf dot fr
We shouldn't use "if" or "else" for this. We should use new keywords for this. It seems simple to implement, but maybe they don't want this because of performance concerns ?
 [2013-02-04 21:34 UTC] sebi at max-vision dot ro
I'd love something like this: if there is at least one iteration, even with break or continue, don't do "else", otherwise, enter the else. 
Another great would be even better, something like "while(..){..}done{...}else{...}"

It could be a new keyword like "whileif".

Anyway, even the first proposed structure would be awesome.
 [2014-10-12 14:24 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2014-10-12 14:24 UTC] nikic@php.net
Closing as Wfx as this feature was rejected in https://wiki.php.net/rfc/loop_or.
 [2016-05-10 13:56 UTC] asd at asd dot asd
Hey, it's an awesome feature everyone would like. Let's reject it!
 [2017-06-17 16:28 UTC] rageclick at gmail dot com
I almost never join conversations or write comments online but I would also love to see this feature as well. It's just nicer, easier to look at and it uses less code which is what I go for. However... if there is a reason behind why you won't do this, I would understand.

while ($result = $get->fetch_assoc()) {
  $in=1;
  echo 'Something';
}
if(!$in){ echo 'Nothing'; }

WHEN I could be doing this

while ($result = $get->fetch_assoc()) {
       echo 'Something'; 
}else{ echo 'Nothing'; }
 [2017-06-27 10:46 UTC] php at pointpro dot nl
This syntax would indeed be great. I see that the vote was not passed at the RFC, but I don't see any argumentation why.

Other languages don't have it is not true, and also not a reason to not add it.

What are arguments against having such a useful construct?
 [2017-06-27 16:21 UTC] bensor987 at neuf dot fr
This syntax is causing problems for some because it violates the KISS principles. Since "else" is used for conditions, and since you can write conditions and loops without curly brackets, it could cause confusion to a lot of people.

I proposed "iterated" (if at least 1 iteration) and "none" ("else") as replacements, but this request has been rejected shortly after...
 [2017-06-27 16:55 UTC] bensor987 at neuf dot fr
Plus, consider the following (bad) code :
<?php
$bool = true;
$rand = rand(1, 5);

if ($bool)
  while ($rand != 4) 
    $rand = rand(1, 5);
else
  echo '!bool';

If "else" for loops is implemented, the behaviour of this code will change. I'm sure there are a lot of code like this. That's another reason people don't like this new use for "else".
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 17:01:29 2024 UTC