Menu
Coddy logo textTech

Adding New Key-Value Pairs

Part of the Fundamentals section of Coddy's PHP journey. Lesson 44 of 71.

You've learned how to modify existing values in an associative array. But what happens when you assign a value to a key that doesn't exist yet? PHP automatically creates it for you.

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

$person["city"] = "Paris";
$person["job"] = "Developer";

echo $person["city"]; // Paris
echo $person["job"];  // Developer
?>

The syntax is the same as modifying—$array["key"] = value—but when the key doesn't exist, PHP adds a new key-value pair to the array instead of updating an existing one.

This is especially useful when building an associative array gradually:

<?php
$settings = [];

$settings["theme"] = "dark";
$settings["language"] = "en";
$settings["notifications"] = true;

echo $settings["theme"]; // dark
?>

Starting with an empty array and adding pairs as needed is a common pattern when collecting data over time or when you don't know all the keys upfront.

challenge icon

Challenge

Easy

Start with an empty associative array called $profile.

Read the following inputs:

  • A string key1 - the first key to add
  • A string value1 - the value for key1
  • A string key2 - the second key to add
  • A string value2 - the value for key2
  • A string key3 - the third key to add
  • A string value3 - the value for key3

Add each key-value pair to the $profile array, then print:

  1. The value associated with key1
  2. The value associated with key2
  3. The value associated with key3

Print each result on a separate line.

Example:

If the inputs are username, alice123, email, alice@example.com, status, and active, the output should be:

alice123
alice@example.com
active

If the inputs are brand, Nike, size, 42, color, and black, the output should be:

Nike
42
black

Try it yourself

<?php
// Read inputs
$key1 = trim(fgets(STDIN));
$value1 = trim(fgets(STDIN));
$key2 = trim(fgets(STDIN));
$value2 = trim(fgets(STDIN));
$key3 = trim(fgets(STDIN));
$value3 = trim(fgets(STDIN));

// Start with an empty associative array
$profile = [];

// TODO: Write your code below
// Add each key-value pair to the $profile array


// Print the values associated with each key
echo $profile[$key1] . "\n";
echo $profile[$key2] . "\n";
echo $profile[$key3] . "\n";
?>
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online PHP compiler