Menu
Coddy logo textTech

Recap - Key-Value Data Store

Part of the Fundamentals section of Coddy's PHP journey — lesson 46 of 71.

challenge icon

Challenge

Easy

Read a line of input containing a JSON object representing a contact's information (e.g., {"name": "Alice", "phone": "555-1234"}).

Then read the following inputs:

  • A string keyToCheck - a key to verify if it exists
  • A string keyToModify - an existing key to update
  • A string newValue - the new value for keyToModify
  • A string newKey - a new key to add
  • A string newKeyValue - the value for newKey

Create an associative array from the JSON input, then perform the following operations:

  1. Check if keyToCheck exists. Print Found if it exists, otherwise print Not found.
  2. Modify the value at keyToModify to newValue.
  3. Add a new key-value pair using newKey and newKeyValue.
  4. Print the updated value at keyToModify.
  5. Print the value at newKey.

Print each result on a separate line.

Example:

If the inputs are {"name": "Alice", "phone": "555-1234"}, email, name, Bob, city, and Paris, the output should be:

Not found
Bob
Paris

If the inputs are {"product": "Laptop", "price": 999}, price, product, Tablet, stock, and 25, the output should be:

Found
Tablet
25

Try it yourself

<?php
// Read the JSON input and convert to associative array
$jsonInput = trim(fgets(STDIN));
$contact = (array)json_decode($jsonInput, true);

// Read the other inputs
$keyToCheck = trim(fgets(STDIN));
$keyToModify = trim(fgets(STDIN));
$newValue = trim(fgets(STDIN));
$newKey = trim(fgets(STDIN));
$newKeyValue = trim(fgets(STDIN));

// TODO: Write your code below
// 1. Check if keyToCheck exists and print "Found" or "Not found"
// 2. Modify the value at keyToModify to newValue
// 3. Add a new key-value pair using newKey and newKeyValue
// 4. Print the updated value at keyToModify
// 5. Print the value at newKey

?>

All lessons in Fundamentals