Arrays in PHP or in many other languages are used to store multiple values in a single variables. Consider a situation where you want to store a list of your friends in your PHP code. You can do this using variables as follows –
Now consider a case where you need to store the city names in our country, this time it’s not 3-4 values they are in hundreds. So, rather than declaring hundred variables, we can simply create an array of size 100.
Advantages of array over variables
- Data can be managed easily.
- Values are easy to locate in array.
- Various searching and sorting algorithms can be implemented within array.
Types of Array
Arrays in PHP can be in of the following types –
- Indexed Array
- Associative Array
- Multidimensional Array
Indexed Array
Indexed Array in PHP stores values with number index i.e. position. The position or index in this case always starts with 0 and they are automatically assigned to the values.
Associative Arrays in PHP
Associative arrays in PHP can have user-defined indexes. This is also called as key-value pair, where keys ca be any string. In such arrays, keys are used to access array values.
Consider the following example
Multidimensional Array
In simple terms a combination arrays within an array is know as multidimensional array. In such arrays, each values is an array in itself. In order to access the elements in multidimensional arrays, multiple indexes are used.
Consider the following code showing multidimensional array –
Printing Arrays in PHP
Array values can be printed using simple echo or print statements, but in order to print complete structure of array, print_r() or var_dump() methods can be used. Consider the following code –
Read Also – Constants in PHP