Chinu Chinu - 1 month ago 8
PHP Question

How to show Price range in PHP?

Code:

$start = 8;
$end = 550;
$step = 100;

for($i=$start; $i<$end; $i=$i+$step){
$firstNum = $i;
$lastNum = $i + $step;
echo $firstNum.' - '.$lastNum;
echo "<br>";
}


Output:

8 - 108
108 - 208
208 - 308
308 - 408
408 - 508
508 - 608


I want to my output should be like-

8 - 100
101 - 200
201 - 300
301 - 400
401 - 500
501 - 600


How to do that in php code?

Answer

While using a $step = 100; you have to round down both range ends to nearest multiple of 100 but with one incremental step, using a if condition will do the job:

for ($i = $start; $i <= ceil($end / $step) * $step; $i++){
    if ($i % $step == 0) {
        echo $start, " - ", $i, PHP_EOL;
        $start = $i + 1;
    }
}

Output:

8 - 100
101 - 200
201 - 300
301 - 400
401 - 500
501 - 600
Comments