HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Loop with enclosing items every 'n' steps

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withstepsloopeveryitemsenclosing

Problem

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 = "";
$closing = "";
$names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff"); 

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

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

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

    if(!$open && !($i % n) && !$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.

Solution

One problem with your solution is that it won't print the last closing ` tag if there are less than $n elements inside the last .

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;
    }
}

Code Snippets

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;
    }
}

Context

StackExchange Code Review Q#82, answer score: 9

Revisions (0)

No revisions yet.