Introduction
One variable holds one value, but real data comes in groups: the marks of a class, the prices in a basket, the words of a sentence. An array holds many values in one variable. PHP arrays are very flexible: they grow and shrink on their own, they can hold any mix of types, and they come with dozens of ready-made functions. In this lesson you will use arrays as simple lists, where the items are numbered from 0. The next lesson shows arrays with names as keys.
How it works
You create an array with square brackets: $nums = [5, 3, 8, 1];. The items have indexes 0, 1, 2 and so on, so $nums[0] is 5 and $nums[3] is 1. To add an item at the end, write $nums[] = 9;. The function count($nums) tells you how many items there are, so the last index is count($nums) - 1. Reading an index that does not exist gives a warning and the value null.
The most useful functions are these:
sort($a)sorts from small to big andrsort($a)from big to small. They change the array itself.array_push($a, $x)adds to the end andarray_pop($a)removes and returns the last item.array_unshift($a, $x)adds to the start andarray_shift($a)removes and returns the first item.in_array($x, $a)tells whether a value is in the array, andarray_search($x, $a)returns its index, orfalse.array_slice($a, $start, $length)copies a part of an array.implode(", ", $a)joins the items into one string, andexplodedoes the opposite.max,minandarray_sumgive the biggest value, the smallest value and the total.print_r($a)prints the whole array in a readable way, which is perfect for checking your work.
An array can hold other arrays. This is how you store a table, also called a two-dimensional array: $grid = [[1, 2, 3], [4, 5, 6]];. Then $grid[1][2] is 6, the item in row 1 and column 2. A foreach loop over $grid gives you one row at a time, and a loop inside it can go over the columns.
Arrays are copied when you assign them. After $b = $a;, changing $b does not change $a. This is different from objects, which you will meet later. Finally, remember that sort renumbers the keys from 0, which is what you want for a list.
Example
<?php
$nums = [5, 3, 8, 1];
$nums[] = 9;
echo count($nums), " items, first ", $nums[0], ", last ", $nums[count($nums) - 1], "\n";
sort($nums);
echo implode(", ", $nums), "\n";
rsort($nums);
echo implode(", ", $nums), "\n";
array_push($nums, 7);
$last = array_pop($nums);
array_unshift($nums, 0);
$first = array_shift($nums);
echo "popped $last, shifted $first\n";
echo in_array(8, $nums) ? "has 8" : "no 8", "\n";
echo array_search(3, $nums), "\n";
print_r(array_slice($nums, 1, 2));
$grid = [[1, 2, 3], [4, 5, 6]];
echo $grid[1][2], "\n";
foreach ($grid as $row) {
echo implode(" ", $row), "\n";
}
echo max($nums), " ", min($nums), " ", array_sum($nums), "\n";Line by line
- An array with four numbers is created, and
$nums[] = 9;adds a fifth. countand the indexes give the size, the first item and the last item.sortandrsortorder the array, andimplodeprints it on one line.- Push, pop, unshift and shift add and remove items at both ends.
in_arrayandarray_searchlook for a value.array_slicecopies two items, andprint_rshows them with their indexes.- A two-dimensional array is printed one row at a time.
max,minandarray_sumsummarise the array.
Expected result
5 items, first 5, last 9
1, 3, 5, 8, 9
9, 8, 5, 3, 1
popped 7, shifted 0
has 8
3
Array
(
[0] => 8
[1] => 5
)
6
1 2 3
4 5 6
9 1 26
In the real world
Arrays hold almost all the data a program handles: the rows returned by a database, the lines of a file, the products of a shop and the items of a menu. Sorting, searching and adding up values are daily jobs. Knowing the array functions lets you do these jobs in one line instead of writing a loop every time.
Common mistakes
- Starting to count at 1. The first index is 0.
- Reading past the end, such as
$nums[count($nums)], which does not exist. - Forgetting that
sortchanges the array and returns only true. - Using
array_searchin anifwithout!== false, so that index 0 looks like "not found".
Best practices
- Use
foreachto visit all items. - Use
print_rorvar_dumpto look inside an array when you debug. - Use
[]to add items; it is shorter thanarray_pushfor a single value. - Compare the result of
array_searchwith=== false.
Summary
An array stores many values under numbered indexes that start at 0. Use [] to add items, count for the size, and functions such as sort, array_pop, in_array, array_slice, implode and array_sum for common jobs. Arrays can hold arrays to make tables, and assigning an array makes a copy.
Quick check
Key takeaways
- An array stores many values under indexes that start at 0.
- Built-in functions add, remove, sort, search and join items.
- Arrays inside arrays make tables.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.