Loop with enclosing items every 'n' steps I'm listing elements with a foreach, and I would like to enclose items in something tag n by n:

$i = 0;
$open = $done = TRUE;
$n = 3;
$opening = "&lt;div&gt;";
$closing = "&lt;/div&gt;";
$names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff"); 

foreach($names as $name) { /** $condition was not a bool. My fault. */

    if($open &amp;&amp; !($i % n)) {
        print $opening;
        $open = FALSE;
        $done = !$open;
    } elseif(!($i % n)) $done = FALSE;

    /** print element. */
    print $name;

    if(!$open &amp;&amp; !($i % n) &amp;&amp; !$done) {
        print $closing;
        $open = TRUE;
        $done = !$open;
    }

    $i++;

}


Do you think this snippet can be improved? It would be better to have fewer check variables such as $open or $done.
One problem with your solution is that it won't print the last closing &lt;/div&gt; tag if there are less than $n elements inside the last &lt;div&gt;.

An approach which fixes that problem and also simplifies the conditional logic for deciding when to print the tags is to chunk the array first using array_chunk and then iterate over the chunks. Now we only need one boolean variable to remember which chunks to surround in tags.

function alternate($names, $n, $opening, $closing) {
    $tag = TRUE;
    foreach(array_chunk($names, $n) as $chunk) {
        if($tag) {
            print $opening;
        }
        foreach($chunk as $name) {
            print $name;
        }
        if($tag) {
            print $closing;
        }
        $tag = !$tag;
    }
}