Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

InspiredPrynce's avatar

Getting Percentage of Numbers

Hello guys, i have a student results processing application that sends scores for processing. Here is a sample of the test array during processing:

$sent_marks = [
  'kick_off' => $request->kick_off == 0 ? null : $request->kick_off,
  'first_test' => $request->first_test == 0 ? null : $request->first_test,
  'project' => $request->project == 0 ? null : $request->project,
  'mid_term' => $request->mid_term == 0 ? null : $request->mid_term,
  'second_test' => $request->second_test == 0 ? null : $request->second_test
];

Some students might be lacking some scores thats why this line is there 'kick_off' => $request->kick_off == 0 ? null : $request->kick_off so if a student score is set to 0 (that is, the person didnt sit for the test, it will be sent as 0, then my system will pick it up as null instead, i just hate storing 0 in the DB) Each of these sent scores cannot be more than 10, and i intend to filter out the NULL values and get the C.A value of the remaining scores which cannot be more than 40 because the exam score is 60 which should total it to 100, So the issue is now how to do what i stated above. Thanks alot!

0 likes
2 replies
bobbybouwmann's avatar

You can simply loop over each value and get the score right?

$sent_marks = [
    'kick_off' => $request->kick_off == 0 ? null : $request->kick_off,
    'first_test' => $request->first_test == 0 ? null : $request->first_test,
    'project' => $request->project == 0 ? null : $request->project,
    'mid_term' => $request->mid_term == 0 ? null : $request->mid_term,
    'second_test' => $request->second_test == 0 ? null : $request->second_test
];

$collection->sum(function ($mark) {
    if ($mark > 10) {
        return 10;
    }
  
    if ($mark < 0) {
        return 0; 
    }
  
    return $mark;
}); // return the total score
InspiredPrynce's avatar

Thank you for your response, what if the scores are all 10, will it return 50 or 40 because the target is to get atleast 40 marks of the sent marks?

Please or to participate in this conversation.