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!
A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.
C style increment and decrement operators represented by ++ and -- respectively are defined in PHP also. As the name suggests, ++ the increment operator increments value of operand variable by 1. The Decrement operator -- decrements the value by 1. Both are unary operators as they need only one operand.
If you declare it inside, it will be a new variable each time it iterates. When that is done, you will need to increment the variable for each iteration, this can be done by either $i++ or $i+=1 . If you wish it to start with 1 and the increase, set it to 1 from start and increase it by 1 at the end of the loop.
In the next line, for loop is declared that starts from 1 and ends when the value of i is less than n and inside this loop the index value of variable i is increment by 2. Inside the loop, the print function is used, which uses variable i to prints its increment value.
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"
<?php
for ($n = 0; $n <= 7; $n++) {
echo '<p>'.($n + 1).'</p>';
echo '<p>'.($n * 2 + 1).'</p>';
}
?>
First paragraph:
1, 2, 3, 4, 5, 6, 7, 8
Second paragraph:
1, 3, 5, 7, 9, 11, 13, 15
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With