PHP Arrays

An array is a list that hold multiple values and is an indispensable tool in programming. An array consists of elements, each of which can hold a value. Each element is referenced by its index (or key).

Initializing Arrays

There are many ways to initialize an array variable. One way is to siply start assigning values to the elements of the array variable.

Since we do not specify any indices, PHP by default assigns the numberic indices 0, 1, and 2:

$languages[] = "English";
$languages[] = "Chinese";
$languages[] = "German";


echo($languages[2]); //Prints "German"

To explicitly specify an index, include it between the brackets:

$languages[0] = "English";
$languages[1] = "Chinese";
$languages[2] = "German";


echo($languages[2]); //Prints "German"

Array elements do not need to be declared sequentially. The following code will create a four-element array with the indices 5, 15, 13, 16:

$languages[5] = "English";
$languages[15] = "Chinese";
$languages[13] = "German";
$languages[] = "Korean";


echo($languages[13]); //Prints "German"
echo($languages[16]); //Prints "Korean"

Since we did not specify an index for the last element, PHP assigned the first available integer that comes after the highest index used so far: 16.

The array() construct provides an alternative way to define arrays. array() receives a comma-delimited list of values to place in the array:

$languages = array("English", "Chinese", "German", "Korean");
echo($languages[2]); //Prints "German"

Again, since we have not specified any indices, our array's element are assigned the default indices. To explicitly specify an index with the array() construct, use the => operator:

$languages = array("English", 3=>"Chinese", "German", "Korean");

echo($languages[0]); //Prints "English"
echo($languages[3]); //Prints "Chinese"
echo($languages[4]); //Prints "German"
echo($languages[5]); //Prints "Korean"

An array indices may also be strings:

$languages = array(
      "en"=>"English",
      "ch"=>"Chinese",
      "de"=>"German",
      "ko"=>"Korean"
);

echo($languages["en"]); //Prints "English"
echo($languages["ko"]); //Prints "Korean"

Multi-Dimensional Arrays

A multi-dimensional array exists when the elements of an array themselves contain arrays.

$things = array(
        "Animals"=>array("dog", "cat"),
        "Insects"=>array("bee", "butterfly")

);

To access the deeply nested elements of a multi-dimensional array, additional sets of brackets are used.

echo($things["Animals"][1]); //Prints "cat"

where $things["Animals"] refer to the array containing the animal names for example.