From: bugs dot php dot net at bjarno dot be
Operating system: N/A
PHP version: Irrelevant
Package: *General Issues
Bug Type: Feature/Change Request
Bug description:Make foreach-else
Description:
------------
A lot of programmers use foreach in order to iterate an array (or
something else) in order to find something. When the element is found,
we can use break; in order to get out of the foreach loop and continue
the execution. There are quite a lot of cases, where you want to do
something if you did not find anything in foreach...
Currently, you could check whether a single variable has changed or not,
but sometimes this is not really the case and the only 100% working
solution is creating an extra variable that is being used as a flag
($foreachEnded = true/false), in order to know how we got out of the
foreach. But this is something that should be a lot nicer when the
language actually has a built-in behaviour for this.
If no else-branch exists for the foreach, it should exhibit the same
behaviour as it currently does, which makes it compatible with existing
php code.
Test script:
---------------
// How it should work...
$list = [1, 2, 3, 4, 5];
foreach ($list as $e) {
if ($e == 3) {
echo("3 has been found!");
break;
}
} else {
echo("3 has not been found!");
}
// Prints... 3 has been found!
// Retrying with $list = [1, 2, 4, 5];
// Prints... 3 has not been found!
--
Edit bug report at https://bugs.php.net/bug.php?id=67843&edit=1
--