如何在PHP For循环中将数字加2 [英] How to increment a number by 2 in a PHP For Loop

查看:421
本文介绍了如何在PHP For循环中将数字加2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码的简化版本:

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

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

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(这显然很简单)

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

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

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

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!

推荐答案

<?php
  for ($n = 0; $n <= 7; $n++) {
    echo '<p>'.($n + 1).'</p>';
    echo '<p>'.($n * 2 + 1).'</p>';
  }
?>

第一段:

1, 2, 3, 4, 5, 6, 7, 8

第二段:

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

这篇关于如何在PHP For循环中将数字加2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆