Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a number by 2 in a PHP For Loop [duplicate]

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!

like image 952
user2586455 Avatar asked Nov 07 '13 08:11

user2586455


People also ask

Can you increment by 2 in a for loop?

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.

How can I increment a number by 1 in PHP?

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.

How do you increment a variable in a while loop?

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.

Can I increment by 2 in a for loop in Java?

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.


3 Answers

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"

like image 153
AntonioAvp Avatar answered Oct 07 '22 03:10

AntonioAvp


<?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
like image 38
Legionar Avatar answered Oct 07 '22 02:10

Legionar


You should use other variable:

 $m=0; 
 for($n=1; $n<=8; $n++): 
  $n = $n + $m;
  $m++;
  echo '<p>'. $n .'</p>';
 endfor;
like image 29
Manolo Avatar answered Oct 07 '22 03:10

Manolo