[PHP-DEV] Allow else after loop structures for,foreach and while?

  99873
July 14, 2017 20:40 tendoaki@gmail.com (Michael Morris)
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 {}
  99874
July 15, 2017 08:57 gmblar@gmail.com (Andreas Treichel)
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 '
    '; foreach($items as $item) { echo '
  • ', $item, '
  • '; } echo '
' } 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.
  99875
July 15, 2017 20:21 netmo.php@gmail.com (Wes)
Hi, please have a look at https://wiki.php.net/rfc/loop_else first.

It has been discussed already.
  99876
July 15, 2017 20:48 netmo.php@gmail.com (Wes)