php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #50532 Lazy-evaluated multiple-array foreach
Submitted: 2009-12-19 12:38 UTC Modified: 2013-03-15 14:57 UTC
Votes:3
Avg. Score:5.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: jsimlo at yahoo dot com Assigned:
Status: Wont fix Package: Arrays related
PHP Version: * OS: *
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: jsimlo at yahoo dot com
New email:
PHP Version: OS:

 

 [2009-12-19 12:38 UTC] jsimlo at yahoo dot com
Description:
------------
I would like to suggest an extended foreach syntax like this:
<?php
foreach ($a, $b, $c as $k => $i)
  echo $i;
?>
Which would result in the same execution as current:
<?php
foreach (array ($a, $b, $c) as $x)
  foreach ($x as $k => $i);
    echo $i;
?>
The reason for requesting this is (simplicity and) possibility of lazy-evaluation of the source arrays. The source arrays can be expressions that take time to compute; or consume large memory each while they exist; and the body of the foreach can break the foreach cycle, rendering a lazy-evaluation quite worth the trouble. Example:
<?php
// several not-so-easy-to-compute arrays
foreach (
  $item1->GetChilds(),
  $item2->GetChilds(),
  $item3->GetParent()->GetChilds(),
  $item3->GetComputeSomethingDifficultChilds()
  as $child
)
   // searching for a child with a special name
   if ($child->GetName() == 'something') break;

// now we got a child of such name (or the last cycled child)
print_r ($child);

Reproduce code:
---------------
---
From manual page: control-structures.foreach
---



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-12-28 12:39 UTC] jani@php.net
-Package: Feature/Change Request +Package: Arrays related -Operating System: irrelevant +Operating System: * -PHP Version: 5.3.1 +PHP Version: *
 [2013-03-15 14:57 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2013-03-15 14:57 UTC] nikic@php.net
I don't think it makes to extend the foreach syntax in that direction. It's hard to understand and rarely useful.

Instead use AppendIterator from SPL (http://php.net/appenditerator).
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC