Req #67843 [Opn->Dup]: Make foreach-else

From: Date: Wed, 10 Jun 2015 12:11:39 +0000
Subject: Req #67843 [Opn->Dup]: Make foreach-else
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-193301@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=67843&edit=1

 ID:                 67843
 Updated by:         cmb@php.net
 Reported by:        bugs dot php dot net at bjarno dot be
 Summary:            Make foreach-else
-Status:             Open
+Status:             Duplicate
 Type:               Feature/Change Request
 Package:            *General Issues
 Operating System:   N/A
 PHP Version:        Irrelevant
-Assigned To:        
+Assigned To:        cmb
 Block user comment: N
 Private report:     N

 New Comment:

This is a duplicate of request #26411.


Previous Comments:
------------------------------------------------------------------------
[2014-08-14 15:57:14] 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!



------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=67843&edit=1


Thread (2 messages)

« previous php.bugs (#193301) next »