How to make loop per tens like this one,
<?php
for ($i=0; $i < 30; $i++) {
if ($i == 1 || $ == 2 ... $i == 10) {
# code...
} elseif ($i == 11 || $ == 12 ... $i == 20) {
# code...
} else {
# code...
}
}
I need 1 2 3 4 5 is different from 11 12 13 14 15 and 21 22 23 24 25
There are several ways you could approach this :
1. Separate them
Since clearly, you're doing different code to the ranges 1-10, 11-20, a,d 21-30, then it would do you good to separate them into several for loops.
for ($i=1; $i <= 10; $i++) {
//code for $i 1-10
}
for ($i=11; $i <= 20; $i++) {
//code for $i 11-20
}
for ($i=21; $i <= 30; $i++) {
//code for $i 21-30
}
2. Put the conditionals inside one for loop, but use <= instead of ==
for ($i=1; $i <= 30; $i++) {
if($i <= 10){
//code for $i 1-10
}
else if($i <= 20){
// code for $i 11-20
}
else{
// code for $i 21-30
}
}
Alternatively, you could use $i > 0 && $i <= 10
for the if
conditions if you prefer or for readability, but the above code does exactly the same with less.
Personally, for your specific example, I would prefer using the first option, as it is much more readable (for me).
How about this:
for($i = 0; $i < 30; $i++) {
switch (floor($i / 10)) {
case 0:
break;
case 1:
break;
default:
break;
}
}