php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #72995 wish: add 'else' to a 'foreach' block
Submitted: 2016-09-01 16:44 UTC Modified: 2016-09-01 22:32 UTC
From: php at richardneill dot org Assigned:
Status: Duplicate Package: Arrays related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: php at richardneill dot org
New email:
PHP Version: OS:

 

 [2016-09-01 16:44 UTC] php at richardneill dot org
Description:
------------
It would be useful if foreach supported an 'else' block, to be evaluated if there are no elements in the array. Just syntactic sugar, but it would make the program easier to read.

This is similar in spirit to the enhancement request in: #60684

Test script:
---------------
//One or other of these initial conditions:
$list = array ("apple", "banana", "cherry");
$list = array();

//Print the list, handle the case where tje array is empty.
foreach ($list as $fruit){
   echo "You have a $fruit.<br>";
}else{
   echo "Sorry, you have no fruit today.<br>";
}

Expected result:
----------------
When the foreach array is empty, control passes into the else block. Otherwise, it doesn't.

This makes the code easier to read, because we don't have to write things like:

$atleastone=false;
foreach ($list as $fruit){
   echo "You have a $fruit.<br>";   
   $atleastone = true;
}
if (!$atleastone){
   echo "Sorry, you have no fruit today.<br>";
}


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-09-01 18:02 UTC] cmb@php.net
You could also write:

  <?php
  if (empty($list)) {
      echo "Sorry, you have no fruit today.<br>";
  } else foreach ($list as $fruit) {
      echo "You have a $fruit.<br>";  
  }
 [2016-09-01 22:32 UTC] requinix@php.net
-Status: Open +Status: Duplicate
 [2016-09-01 22:32 UTC] requinix@php.net
Duplicate of bug #72148, and it of #46240 and #26411.

The feature was considered and declined. https://wiki.php.net/rfc/loop_or
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 18:01:29 2024 UTC