PHP Tutorial · Functions and Arrays · Lesson 18 of 38
PHP Arrays
Indexed, associative and multidimensional arrays.
Indexed arrays
PHP arrays are ordered maps. Indexed arrays use integer keys starting at 0:
<?php
$langs = ["PHP", "JavaScript", "Go"];
echo $langs[0], "\n";
echo count($langs), "\n";
$langs[] = "Rust"; // append
print_r($langs);
Output
PHP
3
Array
(
[0] => PHP
[1] => JavaScript
[2] => Go
[3] => Rust
)Associative arrays
Use string keys to name each value:
<?php
$user = ["name" => "Ada", "email" => "[email protected]"];
$user["role"] = "admin";
echo $user["name"], " is an ", $user["role"], "\n";
var_dump(array_key_exists("email", $user), isset($user["phone"]));
unset($user["email"]);
print_r($user);
Output
Ada is an admin
bool(true)
bool(false)
Array
(
[name] => Ada
[role] => admin
)Multidimensional arrays
Arrays can contain arrays — perfect for rows of data:
<?php
$products = [
["name" => "Laptop", "price" => 999, "tags" => ["tech", "work"]],
["name" => "Mug", "price" => 9, "tags" => ["kitchen"]],
];
echo $products[0]["name"], " has tag ", $products[0]["tags"][1], "\n";
foreach ($products as ["name" => $name, "price" => $price]) {
echo "$name: $$price\n";
}
Output
Laptop has tag work Laptop: $999 Mug: $9
Destructuring
[$a, $b] = $array unpacks values; with keys: ['name' => $name] = $user.
<?php
[$first, $second] = ["gold", "silver", "bronze"];
echo "$first, $second\n";
["host" => $host, "port" => $port] = ["host" => "localhost", "port" => 5432];
echo "$host:$port\n";
[$a, $b] = [1, 2];
[$a, $b] = [$b, $a];
echo "$a $b\n";
Output
gold, silver localhost:5432 2 1
Test yourself
What does $arr[] = 'x'; do?
Replaces the arrayAppends 'x' to the end of the arrayPrepends 'x'Causes an error
Show answer
Answer: Appends 'x' to the end of the array
Practice next
- Array Key Casting · coding problem