Accessing Values by Key
Part of the Fundamentals section of Coddy's PHP journey — lesson 42 of 71.
Now that you understand what associative arrays are, let's learn how to retrieve values from them. Just like indexed arrays use numeric positions, associative arrays use keys inside square brackets.
<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Paris"
];
echo $person["name"]; // Alice
echo $person["age"]; // 25
?>The syntax is $array["key"]—place the key as a string inside the brackets, and PHP returns the associated value. This is much more readable than remembering that the name is at index 0.
You can also store the retrieved value in a variable for later use:
<?php
$product = [
"title" => "Laptop",
"price" => 999
];
$itemName = $product["title"];
echo $itemName; // Laptop
?>The key must match exactly—including capitalization. Using "Name" instead of "name" would cause an error since PHP treats them as different keys.
Sometimes data arrives as a JSON string rather than a PHP array. JSON (JavaScript Object Notation) is a common text format for representing structured data. PHP's built-in json_decode() function converts a JSON string into a PHP value. When you pass true as the second argument, it returns an associative array instead of an object, so you can access values with the familiar $array["key"] syntax.
<?php
$json = '{"name": "Alice", "age": 25}';
$data = json_decode($json, true);
echo $data["name"]; // Alice
echo $data["age"]; // 25
?>Challenge
EasyRead a line of input containing a JSON object representing a book's information (e.g., {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925}).
Then read two more inputs:
- A string
key1representing the first key to access - A string
key2representing the second key to access
To convert the JSON string into an associative array, use the built-in json_decode() function with true as the second argument:
$array = json_decode($jsonString, true);
The second argument true tells PHP to return an associative array instead of an object. Once decoded, you can access values by key just like any associative array, e.g. $array["title"].
Create an associative array from the JSON input, then:
- Access and print the value associated with
key1 - Store the value associated with
key2in a variable called$info - Print the value stored in
$info
Print each result on a separate line.
Example:
If the inputs are {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925}, title, and author, the output should be:
The Great Gatsby
F. Scott FitzgeraldIf the inputs are {"name": "Laptop", "brand": "TechCo", "price": 999}, brand, and price, the output should be:
TechCo
999Cheat sheet
To retrieve values from an associative array, use the key inside square brackets:
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Paris"
];
echo $person["name"]; // Alice
echo $person["age"]; // 25The syntax is $array["key"]. Keys are case-sensitive.
You can store retrieved values in variables:
$product = [
"title" => "Laptop",
"price" => 999
];
$itemName = $product["title"];
echo $itemName; // LaptopUse json_decode($jsonString, true) to convert a JSON string into an associative array. The second argument true tells PHP to return an array instead of an object:
$json = '{"name":"Alice","age":25}';
$data = json_decode($json, true);
echo $data["name"]; // Alice
echo $data["age"]; // 25Try it yourself
<?php
// Read the JSON input
$jsonInput = trim(fgets(STDIN));
// Read the two keys
$key1 = trim(fgets(STDIN));
$key2 = trim(fgets(STDIN));
// TODO: Write your code below
// 1. Create an associative array from the JSON input using json_decode
// 2. Access and print the value associated with $key1
// 3. Store the value associated with $key2 in a variable called $info
// 4. Print the value stored in $info
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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