Req #72995 [Opn->Dup]: wish: add 'else' to a 'foreach' block
| From: | requinix@php.net | Date: | Thu, 01 Sep 2016 22:32:13 +0000 |
| Subject: | Req #72995 [Opn->Dup]: wish: add 'else' to a 'foreach' block | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-203738@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=72995&edit=1
ID: 72995
Updated by: requinix@php.net
Reported by: php at richardneill dot org
Summary: wish: add 'else' to a 'foreach' block
-Status: Open
+Status: Duplicate
Type: Feature/Change Request
Package: Arrays related
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
Duplicate of bug #72148, and it of #46240 and #26411.
The feature was considered and declined. https://wiki.php.net/rfc/loop_or
Previous Comments:
------------------------------------------------------------------------
[2016-09-01 18:02:10] cmb@php.net
You could also write:
<?php
if (empty($list)) {
echo "Sorry, you have no fruit today.<br>";
} else foreach ($list as $fruit) {
echo "You have a $fruit.<br>";
}
------------------------------------------------------------------------
[2016-09-01 16:44:20] php at richardneill dot org
Description:
------------
It would be useful if foreach supported an 'else' block, to be evaluated if there are no
elements in the array. Just syntactic sugar, but it would make the program easier to read.
This is similar in spirit to the enhancement request in: #60684
Test script:
---------------
//One or other of these initial conditions:
$list = array ("apple", "banana", "cherry");
$list = array();
//Print the list, handle the case where tje array is empty.
foreach ($list as $fruit){
echo "You have a $fruit.<br>";
}else{
echo "Sorry, you have no fruit today.<br>";
}
Expected result:
----------------
When the foreach array is empty, control passes into the else block. Otherwise, it doesn't.
This makes the code easier to read, because we don't have to write things like:
$atleastone=false;
foreach ($list as $fruit){
echo "You have a $fruit.<br>";
$atleastone = true;
}
if (!$atleastone){
echo "Sorry, you have no fruit today.<br>";
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=72995&edit=1