- In PHP an array is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.
- Using their index or key arrays are helpful to create a list of elements of similar types, which can be accessed.
- Suppose accordingly we want to store five names and print them and it can be easily done by the use of five different string variables.
- Instead of five string variables, the number rises to a hundred, then it would be really difficult for the developer or user to create so many different variables.
- Also using an index or a key array comes into play and helps us to store every element within a single variable and also allows easy access.
- In PHP an array is created using array() function and basically there three types, they are
-
- Indexed array
- Associative array
- Multidimensional array
Indexed array
- Indexed array is represented by number which starts from 0 and we can store integer, object and string in the PHP array.
- By default, all PHP array elements are assigned to an index number.
Sample Code
Output
Associative Array
- Associative arrays are similar to the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type.
- In PHP we can associate name with each array elements by using => symbol.
Sample Code
Output
Multidimensional Array
- PHP multidimensional array is otherwise known as array of arrays and allows you to store tabular data in an array.
- In the form of matrix PHP multidimensional array can be represented which is represented by row * column.
Sample Code
Output
ID |
Name |
Salary |
1 |
Venkat |
400000 |
2 |
Kishore |
500000 |
3 |
Nizar |
300000 |