Indexed arrays are similar to tables with a single column. An indexed array can contain zero or more elements. In PHP, like in many programming languages, the first element of an array is in the "zeroeth" position. An array with no elements has a zero length.
Arrays are initialized with the
array() function, which can take a list of comma-delimited values that become the elements in the new array. The following lines of code initializes a zero-length array and then adds four elements to the array.
The first line above is actually optional as the second line will create the array if one does not already exist. However, it is a better coding practice to explicitly initialize the array. The
$beatles array could also be created in a single line as follows.
If you know how many elements are in an array, you can append to the array by specifying the index. For example, you could append to the
$beatles array shown above as follows:
However, sometimes you don't know how many elements are in an array. Although you can easily figure this out, doing so requires an extra step. PHP provides an easy way of appending to an array of any length. Simply leave out the index.
Reading from arrays is just a matter of pointing to a specific index or key.
The following code will loop through the entire
$beatles array outputting each element to the browser.
The above code snippets are combined in the following example.