Allow else after loop structures for,foreach and while?

php.internals

Michael Morris

9 years ago
Reading the array coalesce operator concept thread I thought of this. I think I've seen in another language but I'm not sure. Anyway, here goes... Allow else blocks to follow iteration blocks. The else block is executed if no iteration occurs for any reason. foreach ($array as $key => $value) { echo 'Result ' . $key . ' with value: ' . $value . "\n"; } else { echo 'No results'; } There's no reason why this can't be allowed with for and while as well. Obviously do while loops won't be allowed to use this since they always execute at least once. Like the proposal I was reading when I thought about this is largely syntax sugar to make things slightly easier to read and less verbose than the alternative. if (count($array) > 0) { foreach ($array as $key => $value) { echo 'Result ' . $key . ' with value: ' . $value . "\n"; } } else { echo 'No results'; } However the above existing solution doesn't allow $array to be a traversable but non-countable object. We can add other checks, but the verbosity increases. Back to the issue I was reading when I was reading this, it might be possible to allow foreach/else to take a non array argument without tripping off a warning. In that case the expectation is that the programmer gets to control the response, or elect to have no response with else {}

Andreas Treichel

9 years ago
Hi Michael,
> Allow else blocks to follow iteration blocks. The else block is executed > if no iteration occurs for any reason.
I also thought it would been a good idea, but most of the time i need a wrapper in the output like this: if($items) { echo '<ul>'; foreach($items as $item) { echo '<li>', $item, '</li>'; } echo '</ul>' } And this may change the behavior of: if($result) foreach($items as $item) var_dump($item); else echo 'Nothing'; from: if($result) { foreach($items as $item) { var_dump($item); } } else { echo 'Nothing'; } to: if($result) { foreach($items as $item) { var_dump($item); } else { echo 'Nothing'; } } I believe this change is only possible (useful or not) if the curly braces are always required.

Net Mo

9 years ago
Hi, please have a look at https://wiki.php.net/rfc/loop_else first. It has been discussed already.

Net Mo

9 years ago
And also https://wiki.php.net/rfc/loop_or