TExcelTAD
Home › PHP › PHP Arrays

PHP Arrays

An array stores many values in a single variable. Instead of $fruit1, $fruit2 and $fruit3, you keep one $fruits variable and reach each value through its key.

PHP arrays are unusually flexible. The same type works as a list, a dictionary (map), a stack, a queue and even a simple table. Under the hood every PHP array is an ordered map: a sequence of key → value pairs that remembers the order in which you added them.

Creating an array

Modern PHP uses square brackets. The older array(...) syntax still works and does exactly the same thing.

php · try it yourself
<?php
$colors = ['red', 'green', 'blue'];
$sizes = array('S', 'M', 'L'); // older syntax, same result

echo $colors[0] . PHP_EOL;
echo $sizes[2] . PHP_EOL;
echo 'Colors: ' . count($colors) . PHP_EOL;
red
L
Colors: 3

The three kinds of arrays

PHP has only one array type, but people usually talk about three ways of using it:

Kind Keys Example Lesson
Indexed automatic integers 0, 1, 2, … ['tea', 'coffee'] Indexed Arrays
Associative strings you choose ['name' => 'Mai', 'age' => 31] Associative Arrays
Multidimensional any, with arrays as values [[1, 2], [3, 4]] Multidimensional Arrays

You can even mix integer and string keys in one array, although that is rarely a good idea.

Looking inside an array

echo cannot print an array directly. While learning (and debugging), use print_r() for a compact view or var_dump() to also see each value's type.

php · try it yourself
<?php
$order = ['pen', 3, true];

print_r($order);
var_dump($order);
Array
(
    [0] => pen
    [1] => 3
    [2] => 1
)
array(3) {
  [0]=>
  string(3) "pen"
  [1]=>
  int(3)
  [2]=>
  bool(true)
}

Notice that print_r() shows true as 1, while var_dump() tells you it really is a bool.

Tip: print_r($array, true) returns the text instead of printing it — handy for writing it to a log.

Adding, changing and removing items

  • $arr[] = value appends a new item with the next integer key.
  • $arr[key] = value adds or overwrites the item at that key.
  • unset($arr[key]) removes an item (the remaining keys are not renumbered).
php · try it yourself
<?php
$queue = ['Ana', 'Ben'];
$queue[] = 'Chi';        // append
$queue[1] = 'Bao';       // overwrite
unset($queue[0]);        // remove the first item

print_r($queue);
echo 'Items left: ' . count($queue) . PHP_EOL;
Array
(
    [1] => Bao
    [2] => Chi
)
Items left: 2

Arrays are copied on assignment

Unlike objects, arrays are values. Assigning an array to another variable (or passing it to a function) gives the receiver its own copy, so changing one does not affect the other. Use a reference (&) if you really want both names to share the same array.

php · try it yourself
<?php
$original = [1, 2, 3];
$copy = $original;
$copy[] = 4;

$alias = &$original;
$alias[] = 99;

echo implode(', ', $original) . PHP_EOL;
echo implode(', ', $copy) . PHP_EOL;
1, 2, 3, 99
1, 2, 3, 4

PHP makes these copies cheap with copy-on-write: the data is only duplicated at the moment one of the variables is modified.

Useful first functions

Function What it does
count($a) number of items
implode(', ', $a) join values into a string
in_array($v, $a) does the value exist?
array_key_exists($k, $a) / isset($a[$k]) does the key exist?
is_array($x) is the variable an array?

You will meet many more in the Array Functions lesson.

Test yourself

What does $list[] = 'x'; do?

  1. Clears the array
  2. Appends 'x' with the next integer key
  3. Sets key 0 to 'x'
  4. Causes a syntax error

After $b = $a; $b[] = 5; what happens to $a?

  1. It also gets 5
  2. It becomes empty
  3. It is unchanged
  4. It becomes a reference

Which function shows each value together with its type?

  1. echo
  2. print_r()
  3. var_dump()
  4. implode()