Menu
Coddy logo textTech

Adding a Grade to a Student

Part of the Logic & Flow section of Coddy's PHP journey — lesson 35 of 68.

challenge icon

Challenge

Easy

You will receive three inputs: a JSON object representing the existing student gradebook, a student's name, and a grade to add. The gradebook uses student names as keys, with each student having an "id" and "grades" array. The second input is the student's name, and the third input is the grade to add (as a number).

Read all three inputs, convert the JSON string to a gradebook array, locate the specified student, add the new grade to their grades array, and print the updated gradebook using print_r().

Input format:

  • First line: A JSON object representing the existing gradebook (example: {"Alice":{"id":101,"grades":[85,92,78]},"Bob":{"id":102,"grades":[90,88,95]},"Charlie":{"id":103,"grades":[76,84,89]}})
  • Second line: The student's name (example: Alice)
  • Third line: The grade to add (example: 88)

Expected output: The updated gradebook array displayed using print_r(), with the new grade added to the specified student's grades array

Try it yourself

<?php
// Read the gradebook JSON string
$gradebookJson = fgets(STDIN);

// Read the student's name
$studentName = trim(fgets(STDIN));

// Read the grade to add
$grade = intval(fgets(STDIN));

// Convert JSON to array
$gradebook = (array)json_decode($gradebookJson, true);

// TODO: Write your code below
// Locate the student and add the new grade to their grades array


// Output the updated gradebook
print_r($gradebook);
?>

All lessons in Logic & Flow