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

 ID:                 47933
 Comment by:         ni...@php.net
 Reported by:        e dot sand at elisand dot com
 Summary:            Allow foreach to iterate multiple arrays/objects
                     similar to for syntax
 Status:             Open
 Type:               Feature/Change Request
 Package:            Feature/Change Request
 Operating System:   Irrelevant
 PHP Version:        5.2.9
 Block user comment: N
 Private report:     N

 New Comment:

On a side note, this is already possible using MultipleIterator: 
http://de3.php.net/MultipleIterator


Previous Comments:
------------------------------------------------------------------------
[2009-04-09 07:03:32] 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.



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



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

Reply via email to