Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 147 ยท Arrays

Arrays

Learn PHP arrays from scratch - the [] syntax, indexes, adding and removing elements, count, print_r and var_dump, copying, and why every PHP array is an ordered map.

Programs rarely work with just one value. A shopping cart has several products, a class has many students, a log file has thousands of lines. An array stores many values under one variable name, in order, so you can loop over them, count them, sort them and pass them around as a single thing.

Arrays are the most important data structure in PHP. Form fields arrive as arrays, database rows come back as arrays, JSON decodes to arrays, and most of the standard library takes or returns them. This lesson covers the basics of indexed arrays (lists whose keys are 0, 1, 2, โ€ฆ), and one fact that makes PHP different from most languages: every PHP array is really an ordered map of keys to values. The rest of this chapter builds on that, starting with Associative Arrays.

Creating an array

Write an array with square brackets and separate the values with commas. A trailing comma after the last value is allowed, and it makes multi-line lists easier to edit:

PHP Your first arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each value sits at a numeric index that starts at 0, so the first element is $colors[0] and the last of three is $colors[2]. count() returns the number of elements. A PHP array can hold values of any type, even mixed together, though in practice you'll usually keep one kind of value per array.

You'll also meet the older array(...) syntax in existing code: array('red', 'green') is exactly the same as ['red', 'green']. The short form has been available since PHP 5.4 and is what modern code uses.

Reading elements

Access an element with $array[index]. The index can be any expression that produces an integer, such as a variable or a calculation. Reading an index that doesn't exist produces a warning and gives null:

PHP Reading by index, and a missing index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second-to-last line triggers Warning: Undefined array key 10 on purpose: the program keeps running, but the value is null, which usually means a bug. The ?? operator (from Null Coalescing, Ternary and Nullsafe Operators) returns a fallback without any warning when the key is missing.

Negative indexes do not count from the end in PHP. $days[-1] looks for an element whose key is literally -1, finds none, and warns. For the last element use $days[count($days) - 1], array_last($days) (PHP 8.5) or end($days).

Strings can be indexed too ('hello'[1] is 'e', and there negative offsets do count from the end), but that's a byte offset into a string, covered in Strings, not an array.

Adding elements

Empty brackets after the variable append a value at the end, using the next free index. You can also assign to a specific index, which either replaces an element or creates it:

PHP Appending and assigning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last part shows the rule for appending: the next index is one more than the largest integer key so far, not the element count. After $numbers[5] = 60, the array has three elements but the next append goes to index 6. This is the first sign that PHP arrays are maps rather than contiguous lists.

Creating an array with $log[] = โ€ฆ on an undefined variable works, but it's clearer (and avoids surprises if the variable already held something else) to start with $log = [];.

Removing elements

unset($array[index]) removes one element. It does not shift the elements after it down, so a hole remains in the index sequence. If you need a clean 0, 1, 2, โ€ฆ list again, re-index with array_values():

PHP unset leaves a gap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_pop() and array_shift(), along with array_push(), array_unshift() and array_splice() (remove from the middle and close the gap), are covered in Array Functions.

Inspecting arrays: print_r and var_dump

Two built-in functions show what's inside an array:

  • print_r($array) gives a compact, readable view: keys and values only. Pass true as the second argument to get the text back as a string instead of printing it.
  • var_dump($array) shows the type and length of every value as well. Use it when types matter, for instance to tell '1' from 1 or false from ''.
PHP print_r versus var_dump

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In print_r output, true shows as 1, and null, false and '' all show as nothing. var_dump makes them distinct. For a one-line view, json_encode($array) is also handy: ["red","green","blue"].

Looping over an array

The usual way to visit every element is foreach, which you met in foreach Loops. A classic for loop with an index works too, but only when the keys are exactly 0 to count - 1:

PHP foreach and for over a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Prefer foreach: it never reads a missing index, and it works for any keys. Notice also that count() is called once before the for loop and stored in $n, rather than on every iteration.

Arrays are ordered maps

Here's the idea that ties everything together. A PHP array is a list of key => value pairs that remembers the order in which keys were inserted. Indexed arrays are just the special case where PHP chose the keys 0, 1, 2, โ€ฆ for you. You can write the keys yourself with =>:

PHP Keys are always there

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$unordered holds the same pairs as $list, but in a different order. == compares the pairs and says they're equal; === also requires the same order and types, so it says no. array_is_list() (PHP 8.1) tells you whether an array's keys are exactly 0, 1, 2, โ€ฆ in order, which is what JSON calls an array and other languages call a list.

The same structure works with string keys, ['name' => 'Ada', 'age' => 36], which is what the next lesson is about.

Copying arrays

Assigning an array to another variable, or passing it to a function, makes a copy. Changing the copy never affects the original. (Internally PHP shares the memory until one side is modified, a technique called copy-on-write, so copying is cheap until you actually change something.)

PHP Arrays are copied by value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This differs from JavaScript, Python and Java, where assigning an array or list copies only a reference. In PHP, you need an explicit reference (&) to let a function change the caller's array; Parameters and Arguments shows how, and why returning a new array is usually cleaner. Objects are the exception: they behave like handles, as you'll see in Classes, Properties and Methods.

Checking for empty arrays

An empty array is falsy, so if ($items) and if (!$items) work, as does empty($items). When you want to be explicit, compare the count or the value:

PHP
if ($items === []) {
    echo 'Your cart is empty';
}

if (count($items) > 0) {
    echo 'You have ' . count($items) . ' items';
}

$items === [] is clear and fast. empty() also hides warnings for undefined variables, which can mask typos, so many teams prefer the explicit forms.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After $a = ['x', 'y']; $a[7] = 'z'; $a[] = 'w';, at what index is 'w'?

    An append uses one more than the largest integer key so far. The largest key is 7, so 'w' goes to index 8.
  2. 2. What does unset($list[0]) do to $list = ['a', 'b', 'c']?

    unset never re-indexes. Use array_values() afterwards, or array_shift() if you wanted to remove the first element and shift the rest.
  3. 3. What does $days[-1] give for $days = ['Mon', 'Tue']?

    Negative indexes have no special meaning for PHP arrays. The key -1 simply doesn't exist.
  4. 4. After $a = [1, 2]; $b = $a; $b[] = 3;, what is count($a)?

    Arrays are assigned by value. $b is an independent copy, so appending to it leaves $a with two elements. Copy-on-write is only a memory optimization; it never changes the result.

Summary

  • Create arrays with [...]; indexes start at 0 and count() gives the number of elements.
  • $array[] = $value appends at one more than the largest integer key; $array[$i] = $value sets a specific key.
  • Reading a missing key warns and returns null; use ?? for a safe default. Negative indexes don't count from the end.
  • unset() removes an element without re-indexing; array_values() re-indexes.
  • print_r() shows keys and values; var_dump() adds types; json_encode() gives a one-line view.
  • Every PHP array is an ordered map of keys to values; array_is_list() checks for a plain 0, 1, 2, โ€ฆ list.
  • Arrays are copied on assignment and when passed to functions.

Next: Associative Arrays, where you choose your own keys and use arrays as dictionaries and records.