如何在 PHP For 循环中将数字增加 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19831399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:07:22  来源:igfitidea点击:

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

phpfor-loopincrement

提问by user2586455

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.

我希望循环运行 8 次,并且我希望第一段中的数字随着每个循环增加 1,例如

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

1, 2, 3, 4, 5, 6, 7, 8(这显然很简单)

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

但是,我希望第二段中的数字随着每个循环增加 2,例如..

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

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.

我不知道如何在每个循环中使第二段中的数字增加 2。如果我将其更改为 $n++,则它会增加 2,但它只会使循环运行 4 次而不是 8 次。

Any help would be much appreciated. Thanks!

任何帮助将非常感激。谢谢!

采纳答案by Legionar

<?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

回答by AntonioAvp

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"

"+=" 您可以根据需要增加或减少变量。"$i+=5" 或 "$i+=.5"

回答by Manolo

You should use other variable:

您应该使用其他变量:

 $m=0; 
 for($n=1; $n<=8; $n++): 
  $n = $n + $m;
  $m++;
  echo '<p>'. $n .'</p>';
 endfor;

回答by Oladimeji Ajeniya

Simple solution

简单的解决方案

<?php
   $x = 1;
     for($x = 1; $x < 8; $x++) {
        $x = $x + 1;
       echo $x;
     };    
?>

回答by Manuel

Another simple solution with +=:

另一个简单的解决方案+=

$y = 1;

for ($x = $y; $x <= 15; $y++) {
  printf("The number of first paragraph is: $y <br>");
  printf("The number of second paragraph is: $x+=2 <br>");
} 

回答by user2963963

<?php    
     $x = 1;

     for($x = 1; $x < 8; $x++) {
       $x = $x + 2;
       echo $x;
     };
?>