PHP: Is there an elegant way to foreach through multiple items (groups) at a time?

Posted by acheong87 on Stack Overflow See other posts from Stack Overflow or by acheong87
Published on 2012-10-28T10:56:09Z Indexed on 2012/10/28 11:00 UTC
Read the original article Hit count: 226

Filed under:
|

Given an array of N items:

$arr = array('a', 'b', 'c', 'd', 'e', 'f');

What's the most elegant way to loop through in groups of M items (assuming N is divisible by M)?

I tried

foreach (array_chunk($arr, 2) as list($first, $second)) {
    // do stuff with $first and $second
}

but this resulted in a syntax error.

In other words, I want to emulate what in Tcl would look like this:

set arr [a b c d e f]
foreach {first second} $arr {
    // do stuff with $first and $second
}

For now I've resorted to the obvious measure:

foreach (array_chunk($arr, 2) as $group) {
    $first  = $group[0];
    $second = $group[1];
    // do stuff with $first and $second
}

But I'm hoping someone has a more elegant method...

© Stack Overflow or respective owner

Related posts about php

Related posts about foreach