Menu
Coddy logo textTech

Modifying Values by Key

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

Just like you learned to modify indexed array elements by their position, you can update values in associative arrays using their keys. The syntax is identical—assign a new value to an existing key.

<?php
$person = [
    "name" => "Alice",
    "age" => 25,
    "city" => "Paris"
];

$person["age"] = 26;
$person["city"] = "London";

echo $person["age"];  // 26
echo $person["city"]; // London
?>

When you assign a value to a key that already exists, PHP simply replaces the old value with the new one. The key itself remains unchanged—only its associated value is updated.

This is useful when data needs to change over time. For example, updating a user's status, changing a product's price, or correcting information that was entered incorrectly. The key acts as a stable reference point while the value can be modified as needed.

challenge icon

Challenge

Easy

Read a line of input containing a JSON object representing a product's information (e.g., {"name": "Laptop", "price": 999, "stock": 50}).

Then read three more inputs:

  • A string key1 - the first key to update
  • A string value1 - the new value for key1
  • A string key2 - the second key to update
  • A string value2 - the new value for key2

Create an associative array from the JSON input, then:

  1. Update the value associated with key1 to value1
  2. Update the value associated with key2 to value2
  3. Print the updated value at key1
  4. Print the updated value at key2

Print each result on a separate line.

Example:

If the inputs are {"name": "Laptop", "price": 999, "stock": 50}, price, 1099, stock, and 45, the output should be:

1099
45

If the inputs are {"city": "Paris", "country": "France", "population": 2000000}, city, London, country, and UK, the output should be:

London
UK

Cheat sheet

To update values in associative arrays, assign a new value to an existing key:

<?php
$person = [
    "name" => "Alice",
    "age" => 25,
    "city" => "Paris"
];

$person["age"] = 26;
$person["city"] = "London";

echo $person["age"];  // 26
echo $person["city"]; // London
?>

When you assign a value to a key that already exists, PHP replaces the old value with the new one. The key remains unchanged—only its associated value is updated.

Try it yourself

<?php
// Read the JSON input
$jsonInput = trim(fgets(STDIN));

// Read the keys and values to update
$key1 = trim(fgets(STDIN));
$value1 = trim(fgets(STDIN));
$key2 = trim(fgets(STDIN));
$value2 = trim(fgets(STDIN));

// Convert JSON to associative array
$product = (array)json_decode($jsonInput, true);

// TODO: Write your code below
// 1. Update the value associated with key1 to value1
// 2. Update the value associated with key2 to value2
// 3. Print the updated values

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals