Types of Arrays in PHP
In PHP, there are two types of Arrays. A Numerical or an Indexed Array and the other is an Associative Array.
In Numerical or an Indexed Array, the indexer of the array which is used to determine the position (also known as Key) of the stored data element is an integer which begins at zero. Consider this example:
| Position in Array | Name |
|---|---|
| 0 => | TCP |
| 1 => | IP |
| 2 => | DNS |
| 3 => | HTTP |
| 4 => | FTP |
| 5 => | SMTP |
In the left column, we are displaying the position of the name of the protocol that is on the right hand side. The position is an integer and is starting at zero. So, if you were to retrieve the name of the protocol which is at 4th position, then the Array will return 'FTP' and not 'HTTP'. In this way PHP uses integers as indexers or the key to store and determine the position of the data element in the Array. So how is it different from an Associative array?
In Associative array, the key or the indexer of the array which is used to refer to the data element is a string and not an integer. Consider this example:
| Abbreviation | Expanded Term |
|---|---|
| TCP => | Transmission Control Protocol |
| IP => | Internet Protocol |
| DNS => | Dynamic Naming System |
| HTTP => | Hyper Text Transfer Protocol |
| FTP => | File Transfer Protocol |
| SMTP => | Simple Mail Transfer Protocol |
In the above example as you can see, we have used strings and not integers to determine the position of the data elements. So, if we query the array for the data element which is stored at the position of 'SMTP' (our key for the data element), the array will return 'Simple Mail Transfer Protocol'.
To summarize, Indexed arrays have integers as their key values while Associative arrays have strings as their keys. Let's move on to our next topic creating arrays in PHP.