PHP: Arrays
What you will learn
PHP arrays are ordered maps — they can serve as indexed arrays, associative arrays (key-value), or both at once.
Indexed arrays
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // apple
echo count($fruits); // 3
$fruits[] = "date"; // adds to end
Short syntax with [] was introduced in PHP 5.4. Older code may use array("a", "b").
Associative arrays (key-value)
$user = [
"name" => "Alice",
"age" => 25,
"active" => true
];
echo $user["name"]; // Alice
$user["role"] = "admin"; // add a new key
The => operator associates a key with a value.
Array operations
$numbers = [3, 1, 4, 1, 5];
sort($numbers); // sort in place
array_push($numbers, 9); // add to end
$popped = array_pop($numbers); // remove from end
$reversed = array_reverse($numbers);
$exists = in_array(4, $numbers); // true
The foreach loop
foreach ($fruits as $fruit) {
echo $fruit;
}
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
Common mistakes
- Using
[]to access strings when you meant{}—$str[0]works but$str{0}is deprecated - Confusing
array_push()with$arr[] = value— the latter is faster and more readable - Thinking PHP arrays are ordered by insertion (they are) — but
sort()re-indexes numeric keys
Quick check below!