Menu Close

Articles

PHP: Arrays

An array is a composite type. Elements of an array are ordered by a key, and can be accessed individually using a key or index enclosed in square brackets like: array[key] or array[x].

Implementation

An array in PHP is actually an ordered map. A map is a set of (key : value) pairs. By default the key is unsigned integer but it can be also a string. Then you can access one value by key using notation: array[key]. An array can be used as a vector, hash table, dictionary, collection, stack or queue. 

Array constructor

An array is created using constructor array(…) or it can be created using square bracket list of elements […]. Elements of the array are separated by comma “,” and can be strings, numbers or objects. 

Example:

Output:

array(3) { [0]=> string(3) “dog” [1]=> string(3) “cat” [2]=> string(3) “rat” } 
array(3) { [0]=> string(3) “dog” [1]=> string(3) “cat” [2]=> string(3) “rat” }

Note: The second notation is available since PHP 5.4

Associative array

If the array is a key-value map the pair is created using symbol “=>” like: “key” => “value”.

Example:

Output:

array(3) { [“pluto”]=> string(3) “dog” [“tom”]=> string(3) “cat” [“jerry”]=> string(3) “rat” }

Array traversal

Array traversal is a technique to read an array element by element in sequential order. For simple array indexed by integer you can use a normal “for” loop with a control variable of type integer. For a map you can use a specialized loop: “foreach”. 

Example 1:

Iteration for a simple vector:

Note: Sequential access is a control flow statement that can be used for an “iterable” object. In our case the “object” is a simple array. The advantage of this method of traversal become obvious for hash maps.

Example 2:

Iteration for a hash map (associative array):

Note: This array traversal is read only. However it is possible to modify values into a hash map using  reference notation for values. That will be &$color instead of $color.

Example 3:

Alter value in hash map using sequential access.

Output:

array(3) { [“a”]=> int(2) [“b”]=> int(4) [“c”]=> int(6) }

Optional index

Some languages count array indexes starting from 0, some are starting from 1. This is default in PHP. Sometimes you can chose to start with a different value. PHP enable optional start value using an intuitive syntax:

Example:

Output:

Array ( [1] => January [2] => February [3] => March )

Array copy/borrow

You can copy an array using “=”. You can also transfer array reference using symbol “&”.

Example:

Notes: Using array reference to transfer large arrays is faster. Therefore is a good practice to transfer array by reference when you call a function, to avoid large data movements and make your program more efficient. However, if you modify an array reference, the original array will also be modified.

Append elements

You can append new elements using assign operator “=” and empty square brackets: [] or use key that do not exist. If the key exist, element is update. If is a new key, a new element will be created.

Output:

a1=Array ( [0] => 3 [1] => 7 ) 
a2=Array ( [a] => 5 [b] => 8 ) 

Remove & Re-index

You can remove elements from array using function: unset(). After this the element no longer exist but gaps in the index may be present. You can use function array_values() to remove index gaps.

Example:

Multidimensional Array

A multidimensional array is possible in PHP. In next example you will learn how to create a html table using what you have learned so far. Observe you can include tags in your “echo” statements to produce valid HTML code.

Example:

Note: The matrix access is similar to array access, except you use two square brackets [x][y], not one as you may do in other languages: [x, y] will not work, but if you do you get an error and you can fix it!

Useful functions

Two more functions are very useful for working with arrays:

  • sort()  : reorder array elements
  • count() : count the numbers of elements in an array

Example:

Output:

Array ( [0] => 1 [1] => 3 [2] => 7 [3] => 8 [4] => 12 )

String Interpolation

By now you should know what is this. It is a method to include a variable into a string without using concatenation operator “.”. Here it is a very curious behavior of PHP: It does support string interpolation for arrays, but if the array is using strings as keys you must notice you must not use quotes for the [key]:

Example:

Note: There are other tricks to learn about interpolation but you need to learn about classes and objects first.  So read the next chapter and then I will post more examples about this subject.

Read next: Classes & Objects