2016-09-22 4 views
-3

私のコードに出力されている数値をすべて加算しようとしていますが、どうすればいいですか?あなたの最初のコードに関するPHPのループで数値を加算しようとしています

$tall1 = 0; 

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

は、開発とテストコード、 'error_reportingの(E_ALL); ini_set( 'display_errors'、1); '。あなたは未定義の変数 '$ tall'についてPHPが文句を言うのを見て、あなたの間違いを見つけやすくするかもしれません。 –

+0

@RiggsFollyもちろん.... –

答えて

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) 
    } 
} 
関連する問題