Recap - Key-Value Data Store
Part of the Fundamentals section of Coddy's PHP journey — lesson 46 of 71.
Challenge
EasyRead 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 forkeyToModify - A string
newKey- a new key to add - A string
newKeyValue- the value fornewKey
Create an associative array from the JSON input, then perform the following operations:
- Check if
keyToCheckexists. PrintFoundif it exists, otherwise printNot found. - Modify the value at
keyToModifytonewValue. - Add a new key-value pair using
newKeyandnewKeyValue. - Print the updated value at
keyToModify. - 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
ParisIf the inputs are {"product": "Laptop", "price": 999}, price, product, Tablet, stock, and 25, the output should be:
Found
Tablet
25Try 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
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic7Arrays Part 2 - Associative
Intro to Associative ArraysAccessing Values by KeyModifying Values by KeyAdding New Key-Value PairsCheck if Key ExistsRecap - Key-Value Data Store2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators