|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2016-09-01 16:44 UTC] 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>";
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 15 22:00:01 2025 UTC |
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>"; }