Help with my "for loop"

Hi everyone

I have a normal “for loop” below that echo the numbers in the loop. However, i only want the "for loop "to echo out the first 30 numbers, thereafter i want it to echo every 10th number i.e 1, 2, 3, 4 5… … 50, 60, 70 80 90 etc.

I am not sure how to do it. Can someone please give me advice on how i can do this.

for ($i=1; $i <= 150; $i++)
	echo" $i <br />";


Thank you very much everyone.

Warm regards


There are probably many ways of achieving what you want to do, but here is one solution which is arguably easier to read, understand and its openness to change in the future will perhaps more obvious if you have to revisit the code.

$singles = range(1,29);
$tens = range(30, 100, 10);  // <- 3 args, the last is the 'step'
$both = array_merge($singles, $tens);

foreach($both as $n)
    echo $n . PHP_EOL;

It exploits a couple of array functions you might not have been aware of (there are about 80 to choose from).

Exactly like you stated the problem:


for ($i=1; $i <= 150; $i++)
    // echo out the first 30 numbers
    // if $i equal to or less than 30, echo $i
    if($i <= 30) {
        echo" $i <br />";

    // thereafter i want it to echo every 10th number
    // if $i divisible by 10, echo $i
    } elseif($i % 10 == 0) {
        echo" $i <br />";



Little bit faster:

    } elseif($i >= 30) { 
        echo" $i <br />"; 
        $i += 9;

and remove the = from the IF. It exploits the fact that the iterator of a FOR is mutable inside the loop.

EDIT: In fact, it’d be faster still if you just made the elseif an else.

You have to learn to walk before you learn to run. :slight_smile: