Looping?

this bit of code


<?php
for ($i=1; $i<=6; $i++) {
    echo "<div>";
    echo "<label for='file".$i."'>Image ".$i.":</label>";
    echo "<input type='file' name='file".$i."' id='file".$i."'></div>";
    echo "\\r\
";
}
?>

which produces


<div><label for='file1'>Image 1:</label><input type='file' name='file1' id='file1'></div> 
<div><label for='file2'>Image 2:</label><input type='file' name='file2' id='file2'></div> 
<div><label for='file3'>Image 3:</label><input type='file' name='file3' id='file3'></div> 
<div><label for='file4'>Image 4:</label><input type='file' name='file4' id='file4'></div> 
<div><label for='file5'>Image 5:</label><input type='file' name='file5' id='file5'></div> 
<div><label for='file6'>Image 6:</label><input type='file' name='file6' id='file6'></div>

but would like it to instead produce


<div><label for='file1'>Image 1:</label><input type='file' name='file1' id='file1'></div> 
<div><label for='file2'>Image 2:</label><input type='file' name='file2' id='file2'></div> 
<div><label for='file3'>Image 3:</label><input type='file' name='file3' id='file3'></div> 
</div><div class="column">
<div><label for='file4'>Image 4:</label><input type='file' name='file4' id='file4'></div> 
<div><label for='file5'>Image 5:</label><input type='file' name='file5' id='file5'></div> 
<div><label for='file6'>Image 6:</label><input type='file' name='file6' id='file6'></div>

How do I change that if statement so I can split up the 6divs in h alf?

Thanks

Since the loop number is hard coded, you might as well hard code the splitting into two 3 time loops:


 <?php
for ($i=1; $i<=3; $i++) {
    echo "<div>";
    echo "<label for='file".$i."'>Image ".$i.":</label>";
    echo "<input type='file' name='file".$i."' id='file".$i."'></div>";
    echo "\\r\
";
}
echo '</div><div class="column">';
for ($i=4; $i<=6; $i++) {
    echo "<div>";
    echo "<label for='file".$i."'>Image ".$i.":</label>";
    echo "<input type='file' name='file".$i."' id='file".$i."'></div>";
    echo "\\r\
";
}
?> 

This will work for any number of iterations:


for ($i=1; $i<=6; $i++) {

    if ($i > 1 && ($i - 1) % 3 == 0) {
        echo "</div><div class=\\"column\\">\\r\
";
    }

    echo "<div>";
    echo "<label for='file".$i."'>Image ".$i.":</label>";
    echo "<input type='file' name='file".$i."' id='file".$i."'></div>";
    echo "\\r\
";
}

thanks

Here’s another way using array_chunk()


// create a spoof array with 7 items
$vals = range(1,7);

// chunk it into 3s
$parts = array_chunk($vals, 3);

// PHP_EOL = add an OS independent line end
foreach($parts as $part){
  foreach($part as $p){
    echo $p. PHP_EOL;
  }
echo 'DIVIDER'. PHP_EOL ;
}

// gives:
1
2
3
DIVIDER
4
5
6
DIVIDER
7
DIVIDER