2D Associative Arrays
Part of the Logic & Flow section of Coddy's PHP journey — lesson 31 of 68.
While you've been working with 2D arrays using numeric indices, you can also create more structured data by using associative arrays at both the main level and within the nested arrays. This approach uses string keys instead of numbers, making your data much more descriptive and easier to understand.
Here's how you create a 2D associative array where each element has meaningful string keys:
<?php
$students = [
"alice" => [
"name" => "Alice Johnson",
"grade" => 92
],
"bob" => [
"name" => "Bob Smith",
"grade" => 87
],
"charlie" => [
"name" => "Charlie Brown",
"grade" => 95
]
];
?>You can also mix approaches, using numeric indices for the main array while keeping associative arrays inside:
<?php
$users = [
["username" => "john_doe", "email" => "john@example.com"],
["username" => "jane_smith", "email" => "jane@example.com"]
];
?>This structure is incredibly powerful for organizing complex data like user profiles, product catalogs, or any scenario where you need to store multiple related properties for each item. The string keys make your code self-documenting and much easier to maintain than remembering numeric positions.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive one input: a 2D associative array representing a product inventory in JSON format. Each product has a unique product ID as the key, and the value is an associative array containing the product's "name" and "price". Read the input, convert the JSON string to a 2D associative array, iterate through all products, and print each product's information in the format: ID: [product_id] - Name: [name] - Price: $[price]
Each product should be printed on a separate line.
Input format: One line containing a JSON object representing the product inventory (example: {"P001":{"name":"Laptop","price":999.99},"P002":{"name":"Mouse","price":25.50},"P003":{"name":"Keyboard","price":75.00}})
Expected output: Each product printed on a separate line in the format ID: [product_id] - Name: [name] - Price: $[price]
Cheat sheet
You can create 2D associative arrays using string keys at both the main level and within nested arrays:
<?php
$students = [
"alice" => [
"name" => "Alice Johnson",
"grade" => 92
],
"bob" => [
"name" => "Bob Smith",
"grade" => 87
]
];
?>You can also mix approaches, using numeric indices for the main array with associative arrays inside:
<?php
$users = [
["username" => "john_doe", "email" => "john@example.com"],
["username" => "jane_smith", "email" => "jane@example.com"]
];
?>String keys make your data self-documenting and easier to maintain than numeric positions.
Try it yourself
<?php
// Read the JSON input
$input = fgets(STDIN);
// Convert JSON to associative array
$inventory = (array)json_decode($input, true);
// TODO: Write your code below to iterate through the inventory and print each product
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting