Chapter 9

Associative Arrays and Structured Data

Real data arrives as records with named fields. Model one record, handle a field that is missing, and process a whole collection of them.

Chapter 9, Associative Arrays and Structured Data

What you will learn

  • Create and update associative arrays.
  • Iterate keys and values with foreach.
  • Use ?? and key-existence checks appropriately.
  • Model real records as arrays of associative arrays.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

9.1 Named Keys

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$contact = ["name" => "Maya", "email" => "maya@example.com"];

$contact["city"] = "Toronto";
$contact["name"] = "Maya A.";

foreach ($contact as $key => $value) {
    echo $key . ": " . $value . PHP_EOL;
}

9.2 Missing Keys and Defaults

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$user = ["name" => "Maya", "role" => null];

echo ($user["nickname"] ?? "none") . PHP_EOL;
var_dump(isset($user["role"]));
var_dump(array_key_exists("role", $user));

$user["role"] ??= "member";
echo $user["role"] . PHP_EOL;

9.3 Collections of Records

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

function cheapest(array $products): array
{
    usort($products, fn (array $a, array $b): int => $a["price"] <=> $b["price"]);

    return $products[0];
}

$products = [
    ["name" => "Lamp", "price" => 18.00],
    ["name" => "Pen", "price" => 1.25],
    ["name" => "Notebook", "price" => 4.50]
];

echo cheapest($products)["name"] . PHP_EOL;
echo $products[0]["name"] . PHP_EOL;

TPRM Lab 9.1: Create and Update a Record

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$contact = [
    "name" => "Maya",
    "email" => "maya@example.com",
    "active" => true
];

$contact["phone"] = "555-0100";
$contact["active"] = false;

echo $contact["name"] . PHP_EOL;
var_dump($contact["active"]);

TPRM Lab 9.2: Iterate Records

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$products = [
    ["name" => "Notebook", "price" => 4.50],
    ["name" => "Pen", "price" => 1.25],
    ["name" => "Lamp", "price" => 18.00]
];

$total = 0;

foreach ($products as $product) {
    $total += $product["price"];
    echo $product["name"] . PHP_EOL;
}

echo "Total: " . number_format($total, 2) . PHP_EOL;

Back to PHP the TPRM Way