Learn Arrays in PHP

An array holds many values in one variable. An indexed array such as ["Fried Rice", "Chicken Noodles", "Iced Tea"] gives each item a number (its index)…

You could store today's orders one by one: $order1 = "Fried Rice";, $order2 = "Chicken Noodles";, $order3 = "Iced Tea";. A fourth order arrives, so you make $order4. Want to know how many orders there are? You have to count the variables yourself. Want to print them all? You need one echo per variable.

An array holds many values at once in one variable. Picture Mrs. Tini's book. One page lists today's orders, numbered in the order they arrived. In PHP, a list whose items are numbered in order is called an indexed array. Another page is a price list: the menu item on the left and its price on the right. A list that pairs names with values, like menu items with their prices, is called an associative array. So instead of $order1, $order2, $order3, you only need one $orders.

Indexed array: numbering starts at 0

This is the list of orders as an indexed array:

<?php
$orders = ["Fried Rice", "Chicken Noodles", "Iced Tea"];

echo $orders[0] . "\n";
echo count($orders) . "\n";
echo $orders[count($orders) - 1] . "\n";
Fried Rice
3
Iced Tea
Index [0] [1] [2]
Item Fried Rice Chicken Noodles Iced Tea

Adding and changing items

This code adds two new items and replaces one item:

<?php
$orders = ["Fried Rice", "Chicken Noodles", "Iced Tea"];

$orders[] = "Crackers";
$orders[1] = "Meatballs";
array_push($orders, "Hot Tea");

echo count($orders);
5

Associative array: names as keys

This is Mrs. Tini's price list as an associative array:

<?php
$prices = [
    "Fried Rice" => 15,
    "Chicken Noodles" => 12,
    "Iced Tea" => 5,
];

echo $prices["Iced Tea"] . "\n";

$prices["Crackers"] = 2;
echo count($prices);
5
4

Seeing the items: print_r and var_dump

echo can't write an array: echo $orders; gives Warning: Array to string conversion and then the word Array. To see the items, use print_r. These are the items of $prices from the section above, after Crackers was added:

print_r($prices);
Array
(
    [Fried Rice] => 15
    [Chicken Noodles] => 12
    [Iced Tea] => 5
    [Crackers] => 2
)

foreach: one at a time

This code writes every menu item in $prices with its price:

foreach ($prices as $menu => $price) {
    echo "$menu: \$$price\n";
}
Fried Rice: $15
Chicken Noodles: $12
Iced Tea: $5
Crackers: $2

foreach runs the code between { and } once for every item of the array. Each time, $menu holds that item's key, and $price holds its value. For an indexed array, foreach ($orders as $order) is enough, and $order holds one item each time. Loops (code that repeats) are covered in full in the Loop lesson.

🤔 The key "1" becomes 1

This array $tables is written with two keys, "1" and 1:

$tables = ["1" => "Budi", 1 => "Sari"];
echo count($tables); // 1

PHP uses a string that holds a plain whole number, such as "1", as an int key. So both keys above are 1, and "Sari" overwrites "Budi". "01" stays a string key because of its leading 0. The key true becomes 1 too.

🤔 Changing items inside a foreach

These two loops try to raise every price by 1:

$prices = [15, 12, 5];

foreach ($prices as $price) {
    $price = $price + 1;      // a copy, $prices does not change
}

foreach ($prices as $i => $price) {
    $prices[$i] = $price + 1; // [16, 13, 6]
}

⚠️ Off-by-one indexes and duplicate keys

TL;DR: An array holds many values in one variable. An indexed array such as ["Fried Rice", "Chicken Noodles", "Iced Tea"] gives each item a number (its index), starting at 0. If that array is stored in $arr, the first item is $arr[0] and the last is $arr[count($arr) - 1]. count() counts the items, $arr[] = ... adds one at the end. An associative array pairs keys with values through =>, and a value is read by its key: $prices["Iced Tea"]. echo can't write an array, so use print_r or var_dump. foreach runs code once for every item. In foreach ($arr as $price), $price is only a copy: change items through the index, $arr[$i]. If you use &$price, which points straight at the item, write unset($price) after the foreach.

⚡ Indexes start at 0

Write:

<?php
$orders = ["Fried Rice", "Chicken Noodles", "Iced Tea"];

echo $orders[0] . "\n";
echo count($orders) . "\n";
echo $orders[count($orders) - 1] . "\n";
Guess first: what does $orders[3] hold?

Nothing. The indexes are 0, 1 and 2, so PHP gives Warning: Undefined array key 3 and writes nothing.

Meaning: An array holds many values in one variable, and every item has a number (its index) starting at 0. $orders[0] is the first item, count() counts the items, and the last item is at count($orders) - 1. $orders[] = ... adds an item at the end.

⚡ Associative array: names as keys

Write:

<?php
$prices = [
    "Fried Rice" => 15,
    "Chicken Noodles" => 12,
    "Iced Tea" => 5,
];

echo $prices["Iced Tea"] . "\n";

Meaning: => pairs a key (left) with a value (right), and the value is read through its key: $prices["Iced Tea"] answers 5.

⚡ echo can't write an array

Guess first: what does echo $orders; write?

Warning: Array to string conversion, then the word Array. The items stay hidden.

Meaning: To see an array's items, use print_r or var_dump, or take one item, for example $orders[0].

What you will learn