php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #46240 Build in foreach else support
Submitted: 2008-10-06 08:57 UTC Modified: 2012-09-22 09:30 UTC
Votes:173
Avg. Score:4.4 ± 1.0
Reproduced:130 of 132 (98.5%)
Same Version:90 (69.2%)
Same OS:88 (67.7%)
From: kjarli at gmail dot com Assigned:
Status: Duplicate Package: Scripting Engine problem
PHP Version: 5.2.6 OS: *
Private report: No CVE-ID:
 [2008-10-06 08:57 UTC] kjarli at gmail dot com
Description:
------------
Each time you want to foreach an array, you first have to check with 
a count or empty if you want to give a message or w/e to notify there 
is no entry to an array (or object if implements like iterator).

If possible add a else option to foreach.




Reproduce code:
---------------
<?php // old style
if(count($myArray) > 0) {
    foreach($myArray as $key => $value) {
    }
}

//new style

foreach($myArray as $key => $value) {
} else {
   // empty array/object
}
(kinda like how smarty implements it)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-09-07 01:13 UTC] john at brahy dot com
Please add a foreach else. It would save so much programming time and eliminate so much room for error. It's so simple... foreach (){} else {}

PLEASE PLEASE PLEASE PLEASE PLEASE PLEASE
 [2009-10-06 08:37 UTC] ptmcnally at gmail dot com
I agree, this would be a nice addition to PHP6.
 [2010-02-13 19:38 UTC] cerlestes at googlemail dot com
To be honest, I'd like to have a general "onFail{}" handler to put after every function, not only foreach.
Like:

----
foreach($arr as $var)
{
    doCode();
}
onFail
{
    failHandling();
}
----

or

----
file("file.txt")
onFail
{
    failHandling();
}
----

Inside of the onFail-brackets a constant __ERROR__ would be available, with further information on the error.

Basically, that onFail-handler would be executed upon receiving the constant FAIL from the function before the onFail-command.

Regards
 [2010-02-13 19:44 UTC] cerlestes at googlemail dot com
ADDITION:

Why I would like to have this is because of the following situation:

----
$test = (float)0; // This would be the return of a function.

// Failhandling
if(!$test)
{
    doFailhandling();
}else ...
----

This method has room for misinterpretations.
Ofc, you could test for "$test === false", but I think a general onFail-handler would be way nicer.

Thanks for reading
 [2010-12-01 15:37 UTC] jani@php.net
-Package: Feature/Change Request +Package: Scripting Engine problem
 [2010-12-20 13:40 UTC] rick dot sketchy at gmail dot com
I have to agree with the OP. foreachelse (or something similar) is really 
needed. I do like the suggestion posted by cerlestes at googlemail dot com:

foreach($arr as $var)
{
    doCode();
}
onFail
{
    failHandling();
}

A fail handler would prove useful,however I can see it may have some 
limitations, in which case an else option on the foreach would be satisfactory. 
Whilst we're at it, it may as well be added to while statements too.
 [2011-02-04 02:30 UTC] pedro at worcel dot com
foreachelse seems ok to me. Onfail is... weird. :)
 [2011-02-18 01:20 UTC] ijrbiz at gmail dot com
Highly agreed with adding a foreach :: else statement, this request would be very 
practical for improved coding structure and follows logical language syntax 
nicely.

foreach ($items as $item) {
	echo $item; // Manage each item, ...
} else {
	echo 'No items present.'; // Manage no items found, ...
}
 [2011-07-12 12:13 UTC] dinumarina at yahoo dot com
Opposing general consensus, I think adding such feature would be semantically 
ambiguous. The foreach function does not fail, it has types it can handle (assoc 
array, object) and that it can't handle (scalar). A function can always return a 
result that may be valid for foreach but not the expected format, so I think 
data sanitizing is best done dilligently. This is just a lazy-man's hack for a 
non-issue. For the function completion status (onFail), there is already such a 
construct: try {throw()} catch(){} which already supersets the imagined onFail 
implementation. Only thing I would hindsight: it would have been SOOO nice if 
php had a false/null/na result convention, as well as an error/exception 
convention and it would actually stick by it. Each module signals completion, 
computability, singular cases and errors as it well pleases.
 [2011-12-22 20:41 UTC] jason at valdron dot ca
I completely disagree about the onFail section.

The foreach else would be useful if there is no item. As a shortcut to 
if(count($elements) == 0).
 [2012-09-22 09:30 UTC] nikic@php.net
Closing as duplicate of https://bugs.php.net/bug.php?id=26411.
 [2012-09-22 09:30 UTC] nikic@php.net
-Status: Open +Status: Duplicate
 [2012-10-17 21:44 UTC] php at yopmail dot com
foreach(){}else{} is a good id but perhaps need to be improved :

this simple example can't be converted to foreachElse (due to <ul/>) :

-------
if(count($data)>0){
    echo "<ul>";
    foreach($data as $item){
        echo "<ul>$item<ul>";
    echo "<ul>";
}
else
{
    echo "<p>No think to see :(</p>";
}
-------
 [2013-01-04 14:51 UTC] riccardo dot mastellone at gmail dot com
Having the 'else' in case of an empty array would be soo nice, please do add this 
option!
 [2013-02-04 08:58 UTC] paul dot cooperman at gmail dot com
So like the try catch in .NET?
 [2013-05-14 12:14 UTC] amseon at web dot de
@[2012-10-17 21:44 UTC] php at yopmail dot com

Thats true, but you could solve it maybe like this:

-------
echo "<ul>";
foreach($data as $item){
    echo "<li>$item</li>";
} else {
    echo "<li>No think to see :(</li>";
}
echo "</ul>";
-------
 
PHP Copyright © 2001-2014 The PHP Group
All rights reserved.
Last updated: Sat Apr 19 17:01:54 2014 UTC