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 {}

Reply via email to