|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2015-06-10 12:11 UTC] cmb@php.net
-Status: Open
+Status: Duplicate
-Assigned To:
+Assigned To: cmb
[2015-06-10 12:11 UTC] cmb@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 22:00:01 2025 UTC |
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!