Req #72995 [NEW]: wish: add 'else' to a 'foreach' block
From: php at richardneill dot org
Operating system:
PHP version: Irrelevant
Package: Arrays related
Bug Type: Feature/Change Request
Bug description:wish: add 'else' to a 'foreach' block
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 bug report at https://bugs.php.net/bug.php?id=72995&edit=1
--
Try a snapshot (PHP 5.4): https://bugs.php.net/fix.php?id=72995&r=trysnapshot54
Try a snapshot (PHP 5.5): https://bugs.php.net/fix.php?id=72995&r=trysnapshot55
Try a snapshot (trunk): https://bugs.php.net/fix.php?id=72995&r=trysnapshottrunk
Fixed in SVN: https://bugs.php.net/fix.php?id=72995&r=fixed
Fixed in release: https://bugs.php.net/fix.php?id=72995&r=alreadyfixed
Need backtrace: https://bugs.php.net/fix.php?id=72995&r=needtrace
Need Reproduce Script: https://bugs.php.net/fix.php?id=72995&r=needscript
Try newer version: https://bugs.php.net/fix.php?id=72995&r=oldversion
Not developer issue: https://bugs.php.net/fix.php?id=72995&r=support
Expected behavior: https://bugs.php.net/fix.php?id=72995&r=notwrong
Not enough info: https://bugs.php.net/fix.php?id=72995&r=notenoughinfo
Submitted twice: https://bugs.php.net/fix.php?id=72995&r=submittedtwice
register_globals: https://bugs.php.net/fix.php?id=72995&r=globals
PHP 4 support discontinued: https://bugs.php.net/fix.php?id=72995&r=php4
Daylight Savings: https://bugs.php.net/fix.php?id=72995&r=dst
IIS Stability: https://bugs.php.net/fix.php?id=72995&r=isapi
Install GNU Sed: https://bugs.php.net/fix.php?id=72995&r=gnused
Floating point limitations: https://bugs.php.net/fix.php?id=72995&r=float
No Zend Extensions: https://bugs.php.net/fix.php?id=72995&r=nozend
MySQL Configuration Error: https://bugs.php.net/fix.php?id=72995&r=mysqlcfg
Thread (3 messages)
- php at richardneill dot org