PHPLesson 5 of 13

Arrays

An array holds many values under one name. Where $city holds one city, $cities can hold a list of them. You build an array with the short syntax: square brackets with items separated by commas. Every item keeps its position, starting from zero.

An array holds many values under one name. Where $city holds one city, $cities can hold a list of them. You build an array with the short syntax: square brackets with items separated by commas. Every item keeps its position, starting from zero.

Indexed arrays use numbers as keys, and PHP assigns them automatically. $cities[0] is the first item, $cities[1] the second. You can read, overwrite, or append items by their index. The count() function tells you how many items the array has.

Associative arrays use named keys instead of numbers. A user record, for example, maps "name" to "Aya" and "age" to 24. The arrow operator => connects each key to its value. You read a value with $user["name"]. This is the array style you will meet constantly in real PHP code.

The foreach loop exists to walk through arrays. foreach ($cities as $city) gives you each value, and foreach ($user as $key => $value) gives you the key and value pair. It is the workhorse of PHP data handling.

Indexed arrays

Square brackets create an array, and numeric indexes start at zero. Adding an item without an index appends it to the end. Use count() instead of counting by hand.

PHP
$cities = ["Tokyo", "Lagos", "Lima"];
echo $cities[0];        // Tokyo
echo count($cities);    // 3
$cities[] = "Oslo";     // adds at the end
echo count($cities);    // 4

Associative arrays

Named keys make arrays readable. Values can be mixed types: strings, numbers, even other arrays. Use isset() or array_key_exists() to check a key safely before reading it.

PHP
$user = [
  "name" => "Aya",
  "age" => 24,
  "admin" => true
];
echo $user["name"]; // Aya
if (isset($user["email"])) {
  echo $user["email"];
}

Syntax

PHP
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
  echo $fruit . "\n";
}
?>

$arr[] Appends, Not $arr[0]

$arr[] = 5 appends to end, while $arr[0]=5 overwrites first. Use [] for push.

PHP
$arr[] = "new";

Good to know

  • Arrays use square brackets: ["a", "b", "c"].
  • Indexed arrays start at position zero.
  • Associative arrays use named keys with =>.
  • foreach walks every item without needing an index.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground