Looping with Keys and Values
Part of the Fundamentals section of Coddy's PHP journey — lesson 50 of 71.
In the previous lesson, you learned how foreach gives you access to each value in an array. But what if you also need the key? This is especially useful when working with associative arrays.
The foreach loop has an extended syntax that provides both the key and value on each iteration:
<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Paris"
];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>This outputs:
name: Alice
age: 25
city: ParisThe syntax foreach ($array as $key => $value) assigns the current key to $key and the corresponding value to $value. You can name these variables anything you like—just keep them descriptive.
This also works with indexed arrays, where the keys are the numeric indices:
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $index => $color) {
echo "$index: $color\n";
}
?>This outputs:
0: red
1: green
2: blueHaving access to both keys and values makes it easy to display labeled data or perform operations that depend on the key.
Challenge
EasyRead a single line of input containing a JSON object representing a product with keys and values (e.g., {"name":"Laptop","price":"999","stock":"25"}).
Use a foreach loop with the key-value syntax to iterate through the product data. Print each key and its corresponding value in the format:
[key] => [value]Print each key-value pair on a separate line.
Example 1:
If the input is {"name":"Laptop","price":"999","stock":"25"}, the output should be:
name => Laptop
price => 999
stock => 25Example 2:
If the input is {"title":"PHP Basics","author":"John","pages":"350"}, the output should be:
title => PHP Basics
author => John
pages => 350Example 3:
If the input is {"city":"Paris","country":"France"}, the output should be:
city => Paris
country => FranceCheat sheet
The foreach loop can provide both the key and value on each iteration using the extended syntax:
foreach ($array as $key => $value) {
// use $key and $value
}Example with an associative array:
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Paris"
];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}Output:
name: Alice
age: 25
city: ParisThis syntax also works with indexed arrays, where keys are numeric indices:
$colors = ["red", "green", "blue"];
foreach ($colors as $index => $color) {
echo "$index: $color\n";
}Output:
0: red
1: green
2: blueTry it yourself
<?php
// Read the JSON input
$input = trim(fgets(STDIN));
// Convert JSON to associative array
$product = (array)json_decode($input, true);
// TODO: Write your code below
// Use a foreach loop with key-value syntax to iterate through the product data
// Print each key and value in the format: [key] => [value]
?>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 Logic2Variables 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 Decisions8Loops
For LoopWhile LoopForeach LoopLooping with Keys and ValuesBreak StatementContinue StatementRecap - Iterating Over Data3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators