Arrays

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 and rsort($a) from big to small. They change the array itself.
  • array_push($a, $x) adds to the end and array_pop($a) removes and returns the last item.
  • array_unshift($a, $x) adds to the start and array_shift($a) removes and returns the first item.
  • in_array($x, $a) tells whether a value is in the array, and array_search($x, $a) returns its index, or false.
  • array_slice($a, $start, $length) copies a part of an array.
  • implode(", ", $a) joins the items into one string, and explode does the opposite.
  • max, min and array_sum give 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

  1. An array with four numbers is created, and $nums[] = 9; adds a fifth.
  2. count and the indexes give the size, the first item and the last item.
  3. sort and rsort order the array, and implode prints it on one line.
  4. Push, pop, unshift and shift add and remove items at both ends.
  5. in_array and array_search look for a value.
  6. array_slice copies two items, and print_r shows them with their indexes.
  7. A two-dimensional array is printed one row at a time.
  8. max, min and array_sum summarise 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 sort changes the array and returns only true.
  • Using array_search in an if without !== false, so that index 0 looks like "not found".

Best practices

  • Use foreach to visit all items.
  • Use print_r or var_dump to look inside an array when you debug.
  • Use [] to add items; it is shorter than array_push for a single value.
  • Compare the result of array_search with === 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

1. What is the index of the first item of an array?
2. Which function removes and returns the last item?
3. What does $grid[1][2] read in $grid = [[1, 2, 3], [4, 5, 6]]?
4. How do you add the value 9 to the end of $a?

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.