I have the loop below which iterates 4 times. Within this look is another which defines my group names. I would like to produce the output
Group 01
Group 02
Group 03
....
Group 15
Group 16
instead of what I currently get
Group 01
Group 02
Group 03
Group 04
Group 01
Group 02
Group 03
Group 04
Group 01
Group 02
Group 03
Group 04
Group 01
Group 02
Group 03
Group 04
Code
foreach ($largegroups as $key => $users) { // loops 4 times
for ($i = 1; $i <= 4; $i++) {
$num = sprintf("%02d", $i);
$groupname = 'Group ' . $num;
}
}
You need to add a counter to the outer loop, and multiply that by 4 before adding $i
to get the group number. For example:
$g = 0;
foreach ($largegroups as $key => $users) { // loops 4 times
for ($i = 1; $i <= 4; $i++) {
$num = sprintf("%02d", $g * 4 + $i);
$groupname = 'Group ' . $num;
}
$g++;
}
You should declare and use a counter to calculate the correct number of a group. For example:
$counter = 0;
foreach ($largegroups as $key => $users) { // loops 4 times
for ($i = 1; $i <= 4; $i++) {
$counter++;
$groupname = sprintf("Group %02d", $counter);
}
}
Also, you can use range()
function to generate group numbers and avoiding of nested loops. For example:
$count = count($largegroups) * 4;
foreach (range(1, $count) as $number) {
$groupname = sprintf(" Group %02d", $number);
}
Two modifications:
1) Add a counter variable which iterates every time inner loop iterates. That is 4 X 4 = 16 times. Increment the counter at the beginning of inner loop. So that we start from 1
to end 16
instead of 0
to 15
.
2) Add str_pad()
function that will add leading 0
for counters less than 10. So Group 1
would become Group 01
.
<?php
$largegroups = ['','','',''];
$c = 0;
foreach ($largegroups as $key => $users) { // loops 4 times
for ($i = 1; $i <= 4; $i++) {
++$c;
$c = str_pad($c, 2, '0', STR_PAD_LEFT);
echo "<br/>".$groupname = 'Group ' . $c;
}
}
Output:
Group 01
Group 02
Group 03
Group 04
Group 05
Group 06
Group 07
Group 08
Group 09
Group 10
Group 11
Group 12
Group 13
Group 14
Group 15
Group 16