3v4l.org

run code in 300+ PHP versions simultaneously
<?php $correctAnswers = [ ['name'=> 1, 'value'=> 4], ['name'=> 1, 'value'=> 1] ]; $submittedStudentData =[ [101, 0, 1, 1], [102, 0, 4, 1] ]; if(!is_array($submittedStudentData)) { $submittedStudentData = json_decode($submittedStudentData); } $s_data = []; for ($index = 0, $c = count($submittedStudentData); $index < $c; $index++){ // get each student data $studentData = $submittedStudentData[$index]; // get the student roll number $studentId = $studentData[0]; // initialize the total result with zero pre value $totalResult = 0; // loop through the student's submitted answer for ($i = 2, $x = count($studentData) ; $i < $x; $i++) { if ((int)$studentData[$i] === (int)$correctAnswers[$i - 2]["value"]) { $totalResult++; } } $s_data[] = ['studentId' =>$studentId, 'scores'=>$totalResult]; // final result for this student } $r = array_reverse($s_data); foreach($r as $d) { echo 'Student with roll number '. $d['studentId'] .' scores '. $d['scores']."\n"; } ?>
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
Student with roll number 102 scores 2 Student with roll number 101 scores 1

preferences:
139.29 ms | 407 KiB | 5 Q