PHP
Summary - Associative arrays
Build a user profile card with associative arrays and foreach.
Associative arrays summary
In this group you learned the basics of associative arrays. You define them with a key-value pair $arr = ["key" => value] and reach a value with $arr["key"]. For a missing key you give a default with ??.
On the function side array_keys() returns the keys, array_values() returns the values, isset() checks a key's presence, and foreach ($arr as $k => $v) walks all pairs. Now we will combine these in a profile card.
How do you build a profile card?
A profile card combines every capability of an associative array: you store the user in a $profile array, list the fields with foreach in order, and check optional fields with isset().
First you list the fixed fields: name, city, hobby. Then you check an optional age field with isset(); if it exists you add a "Age: " line, otherwise you print "Age: unknown". This way missing data does not break the card.
Exercise List the profile fields
Create the $profile associative array with "name" => "Alex", "city" => "London", "hobby" => "football". Use foreach to print each key-value pair as key: value, one per line.
Show example solution
$v\n"; }
Example solution:
<?php
// List the profile fields
$profile = ["name" => "Alex", "city" => "London", "hobby" => "football"];
foreach ($profile as $k => $v) {
echo "$k: $v\n";
}
Exercise Check the age field
Create the $profile associative array with "name" => "Alex" and "city" => "London". Check the "age" key with isset(); if it exists print the value with the prefix Age: , otherwise print Age: unknown.
Show example solution
unknown\n"; }
Example solution:
<?php
// Profile card and age check
$profile = ["name" => "Alex", "city" => "London"];
if (isset($profile["age"])) {
echo "Age: " . $profile["age"] . "\n";
} else {
echo "Age: unknown\n";
}
Test yourself
-
Which function returns all keys of an associative array?
- array_values()
- array_push()
- array_keys()
- array_merge()
Show answer
array_keys() — Correct. array_keys() returns all keys as a numeric array.
Next lesson: Defining functions