Reputation: 43
I want to get final value of $score in the code below
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
$score = 0;
if($value === $kunci){
$score+=1;
echo $score;
}
}
but its produce value
123456789101112131415161718192021
how do I get 21 value only?
Upvotes: 0
Views: 63
Reputation: 41
Initialize $score before the loop and also print the output after loop.
$score = 0;
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci){
$score+=1;
}
}
echo $score;
Upvotes: 0
Reputation: 2104
You need to echo after loop. As below:
$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
Hope it helps you.
Upvotes: 0
Reputation: 21681
Based on what others have said: But just to show you the full code
$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.
Good Luck.
Upvotes: 1