Lesson 3 of 8
Arrays
PHP uses one collection type, the , for both ordered and key-value maps. Learn to create, over and transform arrays.
<?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
$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 -> arrayFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.