在for循环中添加所有先前的数字

时间:2019-02-27 03:42:14

标签: php

我有一个简单的for循环:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Demo parallax effect</title>
  <style>
    .parallax {
      /* The image used */
      background-image: url("http://placekitten.com/410");
      /* Set a specific height */
      min-height: 410px;
      /*    max-width: 100%;*/
      /* Create the parallax scrolling effect */
      background-attachment: fixed;
      background-position: top;
      background-repeat: no-repeat;
      background-size: cover;
      padding: 0px 0px 0px 0px;
    }
    
    body {
      margin: 0;
    }
  </style>
</head>

<body>
  <div class="parallax"></div>

  <div style="height:1000px;background-color: aliceblue;font-size:36px">
    Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

</body>

</html>

哪个输出:

for($i = 1; $i <= 5; $i++) {

    echo $i . "<br>";

}

现在,我要在每个循环上添加所有先前的数字。因此输出应为:

1
2
3
4
5

我该如何实现?

2 个答案:

答案 0 :(得分:3)

只需使用以下命令即可轻松实现结果

$sum = 0; // you need to intillize variable sum here
for($i = 1; $i <= 5; $i++) {
    $sum = $sum + $i; //you can add all the value in sum and echo it.
    echo $sum . "<br>";
}

答案 1 :(得分:0)

<?php
    $total = 0;
    for($i = 1; $i <= 5; $i++) {
        $total = $total + $i;
        echo  $total."<br>";
    }
?>

您可以通过将$ i的值与$ total的值相加