试图在PHP中添加数字for循环

时间:2016-09-22 12:49:55

标签: php for-loop

我试图将我代码中输出的所有数字相加,我该怎么做?

$tall1 = 0;

for ($tall1=0; $tall1 <= 100; $tall1++) { 
    if ($tall1 % 3 == 0) {
        echo $tall1 . " ";
        $tall++;
    }
}

1 个答案:

答案 0 :(得分:2)

$total = 0; //initialize variable

for ($tall1=0; $tall1 <= 100; $tall1++) { 
    if ($tall1 % 3 == 0) {
        echo $tall1 . " ";
        $total += $tall1; //add the printed number to the previously initialized variable. This is the same as writing $total = $total + $tall1;
    }
}

echo "total: ".$total; //do something with the variable, in this case, print it

关于初始代码的一些注意事项:

$tall1 = 0; //you don't need to do this, it is done by the for loop
for (
     $tall1=0; //this is where $tall1 is initialized
     $tall1 <= 100; 
     $tall1++ //this is where $tall1 is incremented every time
       ) { 
    if ($tall1 % 3 == 0) {
        echo $tall1 . " ";
        $tall++; //this variable is not used anywhere. If you meant $tall1, then you don't need to do this, it is done by the for loop. If you did not mean $tall1, but wanted to count how many times the if statement runs, then you need to initialize this variable (place something like $tall=0; at the top)
    }
}