如何在php中获得+ =运算符的最终值?

时间:2019-02-17 06:23:32

标签: php

我想在下面的代码中获得$ score的最终值

    foreach($request->jawaban as $key => $value){
        $soal = Soal::find($key);
        $kunci = $soal->kunci;    
        $score = 0;
        if($value === $kunci){
           $score+=1;

           echo $score;
        }
    }

但是它的生产价值

123456789101112131415161718192021

我如何只获得21个值?

3 个答案:

答案 0 :(得分:1)

根据其他人的说法:只是为了向您展示完整代码

$score = 0; //define this before the loop

foreach($request->jawaban as $key => $value){
    $soal = Soal::find($key);
    $kunci = $soal->kunci;    

    if($value === $kunci) $score+=1; //simplify this, as I am lazy coder.
}

echo $score; //echo the final value, after the loop finishes.

祝你好运。

答案 1 :(得分:0)

您需要在循环后回显。如下:

    $score = 0; //define this variable before loop
    foreach($request->jawaban as $key => $value){
        $soal = Soal::find($key);
        $kunci = $soal->kunci;    
        if($value === $kunci){
           $score+=1;
        }
    }
    echo $score; // echo after loop end

希望它对您有帮助。

答案 2 :(得分:0)

在循环前初始化$ score,并在循环后打印输出。

$score = 0; 
foreach($request->jawaban as $key => $value){
    $soal = Soal::find($key);
    $kunci = $soal->kunci;    
    if($value === $kunci){
       $score+=1;
    }
}
echo $score;