Arrays

Data structure that stores one or more similar data type values in a single variable

 

Data is stored in elements as key / value pairs. The key is also known as the index

 

3 different types of arrays:

  • Numeric array - Utilises a numeric index. Values are stored and accessed in linear fashion
  • Associative array - Utilises strings as index. Values stored in association with key (string) values
  • Multidimensional array - An array containing one or more arrays. Values accessed using multiple indices

Use the array() construct to create an array. Values are automatically assigned to a numerical index, if not specifically defined:

 

array("model", "price", "speed") ;

 

Alternatively, the Big Arrow => notation can be used:

 

array("0" => "model", "1" => "price", "2" => "speed") ;

 

*note: it is possible to assign alternative key values, as long as they are unique, otherwise their values will be overwritten

 

 

Numeric Array

 

Keys start from 0

 

akin to a spreadsheet that has just one column

 

Assigned using the array(); function:

 

or individually assigning specific elements, using the [ ] (aka Array Operator) notation:

 

 

Associative Array

 

Keys must be unique strings

 

akin to a spreadsheet that has just one column and uses named cells for reference (instead of a cell number)

 

or individually assigning specific elements, using the [ ] notation:

 

Multidimensional Arrays

 

An array of arrays

Each element in the array can be an array, and each element in that sub-array can be an array, etc.

Displays:

array(3) {
    ["England"]=>
    array(3) {
        ["Capital"]=>
        string(6) "London"
        ["Population"]=>
        int(40000000)
        ["NationalSport"]=>
        string(7) "Cricket"
    }
    ["Wales"]=>
    array(3) {
        ["Capital"]=>
        string(7) "Cardiff"
        ["Population"]=>
        int(5000000)
        ["NationalSport"]=>
        string(5) "Rugby"
    }
    ["Scotland"]=>
    array(3) {
        ["Capital"]=>
        string(9) "Edinburgh"
        ["Population"]=>
        int(8000000)
        ["NationalSport"]=>
        string(8) "Football"
    }
}

Leave a Reply