php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #47933 Allow foreach to iterate multiple arrays/objects similar to for syntax
Submitted: 2009-04-09 07:03 UTC Modified: -
Votes:2
Avg. Score:3.0 ± 2.0
Reproduced:2 of 2 (100.0%)
Same Version:2 (100.0%)
Same OS:2 (100.0%)
From: e dot sand at elisand dot com Assigned:
Status: Open Package: Feature/Change Request
PHP Version: 5.2.9 OS: Irrelevant
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: e dot sand at elisand dot com
New email:
PHP Version: OS:

 

 [2009-04-09 07:03 UTC] e dot sand at elisand dot com
Description:
------------
Using the for construct, you are able to define/utilize multiple variables:

for ($i = 0, $j = 10; $i < 10; $i++, $j--) {...}

I would like to propose that a similar syntax be allowed for the foreach construct which would allow iterating over multiple arrays/objects at once:

foreach ($array1 as $i => $a, $array2 as $j => $b) {...}

Such syntax and use would be useful when you have multiple arrays that are related, such as may be found with $_POST data when submitting arrays of values.  For example, a form of inventory data where an id, name and quantity may be submitted - all in individual arrays but the indexes/keys would relate across arrays (id[0] -> name[0] -> quantity[0]).

In such an example, you could write a simple foreach iterator as:

foreach ($_POST['id'] as $key => $id, $_POST['name] as $name, $_POST['quantity'] as $qty) {...}

This would save having to traditionally define $name and $qty within the foreach loop like so:

$name = $_POST['name'][$key];
$qty = $_POST['quantity'][$key];

That is just a simple example however.  As the proposed changes would allow iterating over multiple arrays at once, it could indeed save considerable lines of code.

The only issues to debate with regards to this proposition is what happens if not all arrays being iterated have the same number of members.  The other issue is the syntax, should http://bugs.php.net/bug.php?id=44530&edit=2 be considered - perhaps using ; instead of , to separate the arrays would be simple enough.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-05-20 00:37 UTC] nikic@php.net
On a side note, this is already possible using MultipleIterator: http://de3.php.net/MultipleIterator
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Nov 24 05:01:32 2024 UTC