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 |
- An array is written inside square brackets, and its items are separated by commas.
- Every item has a number, called its index, and numbering starts at 0.
$orders[0]is the first item. count($orders)counts the items: 3.- The last item is at index
count($orders) - 1, which is 2.$orders[3]doesn't exist: PHP givesWarning: Undefined array key 3and writes nothing.
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
$orders[] = "Crackers";(empty square brackets) adds a new item at the end, with the next index, 3.$orders[1] = "Meatballs";overwrites the item at index 1: Chicken Noodles becomes Meatballs.array_push($orders, "Hot Tea")is the same as$orders[] = "Hot Tea".- So
countanswers 5: the first three items, plus Crackers and Hot Tea. Becausecountgrows too,$orders[count($orders) - 1]always takes the last item, however many items there are.
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
=>pairs a key (left) with a value (right). Keys are usually strings.- A value is read through its key:
$prices["Iced Tea"]answers 5. In the same way, in$arr = ["a" => 1, "b" => 2],$arr["b"]answers 2. - A new key adds an item:
$prices["Crackers"] = 2;, socountanswers 4. Writing to a key that already exists overwrites its value.
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
)
print_rwrites every key and its value, easy to read.var_dump($orders)writes the number of items (array(3) {), then the index, type and length of each one, such asstring(10) "Fried Rice". Usevar_dumpwhen you also need the type of each item.
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]
}
- In the first loop,
$priceis only a copy of each item, so$pricesdoes not change. In the second loop,$iholds the index of each item, and$prices[$i] = ...writes straight into the array. - There's also
foreach ($prices as &$price): the&makes$pricepoint straight at the item in the array, not at a copy. This way of pointing is called a reference. But after the loop,$pricestill points at the last item. If you use$priceagain in a laterforeach, the last item is overwritten:[16, 13, 6]becomes[16, 13, 13].unset($price);deletes the variable$price, so its link to the array is gone too. Write that line right after a loop with&.
⚠️ Off-by-one indexes and duplicate keys
- Indexes start at 0. The last item is at
count($arr) - 1, notcount($arr). - echo on an array. All you get is
Arrayand a Warning. Useprint_r,var_dump, or take one item. - Duplicate keys. A key written twice,
"1"and1included, keeps only the last value. &withoutunset. A reference that remains after the loop quietly overwrites the last item in the next loop.
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].