What you will learn
- Create, index, append, and iterate indexed arrays.
- Use array functions for common collection operations.
- Avoid false-versus-zero mistakes when searching arrays.
- Understand when an operation changes an array in place.
The code from this chapter
Type these programs yourself. The predictions below are the exercises; the explanations are in the book.
8.1 Indexed Arrays
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$scores = [70, 85, 92];
$scores[] = 64;
echo count($scores) . PHP_EOL;
echo $scores[0] . PHP_EOL;
echo $scores[count($scores) - 1] . PHP_EOL;
8.2 Useful Array Functions
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$temperatures = [18.5, 22.0, 15.5, 30.0];
echo min($temperatures) . " " . max($temperatures) . PHP_EOL;
echo array_sum($temperatures) / count($temperatures) . PHP_EOL;
$sorted = $temperatures;
sort($sorted);
echo implode(", ", $sorted) . PHP_EOL;
echo implode(", ", $temperatures) . PHP_EOL;
Type this one as well, and predict it before you run it.
<?php
declare(strict_types=1);
$names = ["Maya", "Noah", "Ava"];
$upper = array_map("strtoupper", $names);
$long = array_filter($names, fn (string $name): bool => strlen($name) > 3);
echo implode(", ", $upper) . PHP_EOL;
echo implode(", ", $long) . PHP_EOL;
var_dump(in_array("Ava", $names, true));
$last = array_pop($names);
echo $last . " removed, " . count($names) . " left" . PHP_EOL;
8.3 Searching Carefully
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$names = ["Maya", "Noah"];
var_dump(array_search("Maya", $names, true));
var_dump(array_search("Ava", $names, true));
var_dump(in_array("Noah", $names, true));
TPRM Lab 8.1: Modify an Indexed Array
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$fruits = ["apple", "banana", "cherry"];
$fruits[] = "date";
$fruits[1] = "blueberry";
foreach ($fruits as $fruit) {
echo $fruit . PHP_EOL;
}
TPRM Lab 8.2: Search Without Losing Index Zero
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$items = ["pen", "book", "lamp"];
$index = array_search("pen", $items, true);
if ($index !== false) {
echo "Found at index " . $index . PHP_EOL;
} else {
echo "Not found" . PHP_EOL;
}