Arrays
| Create an array | |
| Read by offset | |
| Append elements | |
| Loop over arrays |
Create an array
An array stores an ordered list of values under one name. The short [] syntax builds one in a single expression, and positions count from zero. The companion page Arrays in PHP shows more array forms.
$colors = ["red", "green", "blue"]; $empty = []; var_dump(count($colors));
Read by offset
Square brackets read one element by its position: $colors[0] is the first item, $colors[2] the third. Reading a missing offset raises a warning and evaluates to null, so check long-lived data with isset first.
$colors = ["red", "green", "blue"]; echo $colors[0]; echo $colors[2];
Append elements
Empty brackets append after the last element: $cart[] = "book" adds one more item and numbers it automatically. This is how lists grow one element at a time, for example while reading rows or collecting input.
$cart = []; $cart[] = "book"; $cart[] = "pen"; echo count($cart);
Loop over arrays
The foreach loop visits every element in order and needs no counter. A classic for loop with an index works too, and fits when the position itself drives the logic.
$cart = ["book", "pen"]; foreach ($cart as $item) { echo $item; } for ($i = 0; $i < count($cart); $i++) { echo $cart[$i]; }
Next: Associative arrays
Article author: Arthur Isaev