How to increment a number by 2 in a PHP For Loop

user2586455 picture user2586455 · Nov 7, 2013 · Viewed 101.8k times · Source

The following is a simplified version of my code:

<?php for($n=1; $n<=8; $n++): ?>
    <p><?php echo $n; ?></p>
    <p><?php echo $n; ?></p>
<?php endfor; ?>

I want the loop to run 8 times and I want the number in the first paragraph to increment by 1 with each loop, e.g.

1, 2, 3, 4, 5, 6, 7, 8 (this is obviously simple)

However, I want the number in the second paragraph to increment by 2 with each loop, e.g...

1, 3, 5, 7, 9, 11, 13, 15

I can't figure out how to make the number in the second paragraph increment by 2 with each loop. If I change it to $n++ then it increments by 2, but it then makes the loop run only 4 times instead of 8.

Any help would be much appreciated. Thanks!

Answer

AntonioAvp picture AntonioAvp · Jun 16, 2016

You should do it like this:

 for ($i=1; $i <=10; $i+=2) 
{ 
    echo $i.'<br>';
}

"+=" you can increase your variable as much or less you want. "$i+=5" or "$i+=.5"