Sage-Code Laboratory
index<--

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. This 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 a literal constant that looks like a square bracket list of elements separated by comma []. Elements can be of same type or mixed: strings, numbers or objects. 

Example:

<?php
// using constructor
$a = array("dog", "cat", "rat");
var_dump($a);
echo "<br>";
// alternative notation
$b = ["dog", "cat", "rat"];
var_dump($b);
?>

Note: The second notation is available since PHP 5.4

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" }

Associative array

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

Example:

<?php
// hash map constructor
$a = array(
"pluto" => "dog",
"tom" => "cat",
"jerry" => "rat");
var_dump($a);
?>

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:

<?php
$a = [2,4,6,8,10]; // array literal
$c = count($a); // number of elements
// access by index
for ($i = 0; $i < $c; $i++) {
    echo $a[$i], ",";
}
echo "<br>";
//sequential access
foreach ($a as $e) {
    echo $e, ",";
}
?>

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):

<?php
// hash map constructor
$cars = ["Toyota" => "red"
        ,"Chevrolet" => "green"
        ,"Volvo" => "silver"
        ];
//sequential access
foreach ($cars as $make => $color) {
    echo "$make => $color","<br>";
}
?>

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.

<?php
// hash map constructor
$test = ["a" => 0
        ,"b" => 0
        ,"c" => 0
        ];
//sequential acess
$v = 2;
foreach ($test as $key => &$value) {
    $value = $v;//alter each value
    $v += 2; //prepare next value
}
// hash map is modified:
var_dump($test);
?>

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:

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

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:

<?php
$a1 = array(1, 2, 3);
//assign array copy
$a2 = $a1;
$a2[0] = 8; // change first element,
echo "a2=";print_r($a2); echo "<br>";
echo "a1=";print_r($a1); echo "<br>"; //unchanged
echo "<br>";
//assign array reference
$a3 = &$a1;
$a3[0] = 5; // change first element,
echo "a3=";print_r($a3); echo "<br>";
echo "a1=";print_r($a1); echo "<br>"; //changed
?>

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.

<?php
/* create simpel vector */
$a1 = array(); //declare empty array
$a1[] = 3; //new element
$a1[] = 7; //new element
echo "a1=";print_r($a1); echo "<br>";
/* create associative array */
$a2 = []; //declare empty array
$a2["a"] = 5; //new element
$a2["b"] = 8; //new element
echo "a2=";print_r($a2); echo "<br>";
?>

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:

<?php
/* create simpel vector */
$a = [1,2,3,4,5]; //declare empty array
echo "before:";print_r($a); echo "<br>";
/* remove 2 elements */
unset($a[1]);
unset($a[3]);
echo "after:";print_r($a); echo "<br>";
/* reindex array */
$a = array_values($a);
echo "reorder:";print_r($a); echo "<br>";
?>

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:

<?php
/* define a matrix with 3x3 = 9 elements */
$m = array(
    array(0,1,2)
   ,array(3,4,5)
   ,array(6,7,8)
);
/* modify diagonal elements */
$m[0][0] = 1;
$m[1][1] = 1;
$m[2][2] = 1;
/* making a table with bordr */
echo '<table style="border: solid;">';
foreach ($m as $row) {
    echo "<tr>";
    foreach ($row as $elm) {
        echo '<td width="14px", height="14px" style="border: 1px solid">';
        echo $elm;
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>

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:

Example:

<?php
/* define a matrix with 3x3 = 9 elements */
$a = [3, 8, 12, 7, 1];
sort($a); //reorder values
print_r($a); //array is modified
?>

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:

<?php
// hash map constructor
$cars = ["Toyota" => "red"
        ,"Chevrolet" => "green"
        ,"Volvo" => "silver"
        ];
// string concatenation
echo "Toyota is ". $cars["Toyota"], "<br>";
// string interpolation
echo "Chevrolet is $cars[Chevrolet]", "<br>";
?>

Note: There are other tricks about interpolation but you need to learn first about classes and objects. So if you are not tired, please read the next chapter. I will post more examples about interpolation later.


Read next: Classes & Objects