Thoughts on adopting Python's for/foreach else construct.

php.internals

Michael Morris

6 years ago
I don't remember if this has been discussed before, but I've been working with some listing code and wishing for a cleaner way to do this <?php if (count($a) === 0) { // code for no results } else { foreach( $a as $key => $value) { // code for iteration } } ?> How difficult would it be to make the following work in the interpreter? <?php foreach($a as $key => $value) { // code for iteration } else { // code for no results } ?> The code of the else clause executes if the foreach is never entered regardless of the reason (provided the code didn't outright crash) Thoughts.

Christian Schneider

6 years ago
Am 25.02.2020 um 20:18 schrieb Michael Morris <tendoaki@gmail.com>:
> How difficult would it be to make the following work in the interpreter? > > <?php > foreach($a as $key => $value) { > // code for iteration > } > else { > // code for no results > } > ?> > > The code of the else clause executes if the foreach is never entered > regardless of the reason (provided the code didn't outright crash)
I like the idea. And I think it makes more sense than what Python actually does: With Python the else clause is executed if the loop is not exited with a break. https://book.pythontips.com/en/latest/for_-_else.html So, yes, I would like a foreach .. else but not the Python way ;-) - Chris

Nikita Popov

6 years ago
On Tue, Feb 25, 2020 at 8:19 PM Michael Morris <tendoaki@gmail.com> wrote:
> I don't remember if this has been discussed before, but I've been working > with some listing code and wishing for a cleaner way to do this > > <?php > if (count($a) === 0) { > // code for no results > } > else { > foreach( $a as $key => $value) { > // code for iteration > } > } > ?> > > How difficult would it be to make the following work in the interpreter? > > <?php > foreach($a as $key => $value) { > // code for iteration > } > else { > // code for no results > } > ?> > > The code of the else clause executes if the foreach is never entered > regardless of the reason (provided the code didn't outright crash) > > Thoughts. >
See https://wiki.php.net/rfc/loop_else and https://wiki.php.net/rfc/loop_or for previous proposals on the topic. I believe an important concern from previous discussions was that this breaks BC in a really bad way, due to the dangling else conflict. Which is why the latter proposal used "or" instead of "else". Regards, Nikita