PhPHP · Lesson 3 of 8

Arrays — PHP's Swiss Army Knife

PHP has one collection type doing the job of lists, dictionaries, sets, and tuples: the array. Master it and you've mastered half of PHP.

PHP
<?php
// List-style (sequential integer keys):
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0];          // apple
$fruits[] = "date";       // append
count($fruits);           // 4

// Map-style (string keys) — an 'associative array':
$student = [
    "name"  => "Ada",
    "age"   => 17,
    "grade" => 95,
];
echo $student["name"];    // Ada
$student["email"] = "ada@example.com";   // add a key

// Both styles in foreach:
foreach ($fruits as $fruit) { echo $fruit; }
foreach ($student as $key => $value) {
    echo "$key: $value\n";
}
PHP
<?php
$nums = [3, 1, 4, 1, 5, 9, 2, 6];

sort($nums);                        // sorts in place
in_array(5, $nums);                 // true
array_search(9, $nums);             // index of 9

// The functional trio:
$doubled = array_map(fn($n) => $n * 2, $nums);
$evens   = array_filter($nums, fn($n) => $n % 2 === 0);
$sum     = array_reduce($nums, fn($acc, $n) => $acc + $n, 0);

// Slicing and merging:
array_slice($nums, 0, 3);           // first three
array_merge($nums, [7, 8]);
implode(", ", $fruits);             // array -> string
explode(",", "a,b,c");              // string -> array
✦ Tip
PHP has 80+ array_* functions — before writing a loop, check if one exists. fn($x) => ... is the short arrow-function syntax (PHP 7.4+); it auto-captures outer variables.