php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #67843 Make foreach-else
Submitted: 2014-08-14 15:57 UTC Modified: 2015-06-10 12:11 UTC
Votes:2
Avg. Score:2.5 ± 1.5
Reproduced:1 of 2 (50.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: bugs dot php dot net at bjarno dot be Assigned: cmb (profile)
Status: Duplicate Package: *General Issues
PHP Version: Irrelevant OS: N/A
Private report: No CVE-ID: None
 [2014-08-14 15:57 UTC] bugs dot php dot net at bjarno dot be
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!


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [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
This is a duplicate of request #26411.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 17:01:29 2024 UTC