What is PHP Array?
In simple words – An array is a data structure that stores one or more similar type of values in a single value. PHP array is an ordered map (contains the value on the basis of a key). It is used to hold multiple values of similar type in a single variable.
Why need Array Methodology?
For example, if you want to store 1000 numbers, then instead of defining 1000 variables. In this condition, You can use Array Methodology. Because It is easy to define an Array of 1000 length.
PHP offers us three types of Array:-
- Indexed Array – ( Arrays with a numeric index)
- Associative Array – (Arrays with named keys)
- Multidimensional Array – (Arrays containing one or more arrays)
-
PHP Indexed Array
A PHP array elements are represented with a numeric index and By default, it always starts from 0. This is known as the Indexed array. These arrays can store number, string also. Values are accessed and stored in linearly.
In PHP, we have two ways for defining Indexed Array-
-
PHP Associative Array
The PHP associative arrays are similar as PHP Indexed arrays in functionality but they have a different index. PHP Associative arrays have their index as strings so that’s why values and key have the strong relationship between them. PHP Associative Arrays can stores element values in association with key values instead of strict linear index order. And here you can associate a name with each array elements in PHP by using “ => “ symbol.
Let’s Understand it as an Example-
To store the marks of Students in an array, we could use the associative array instead of numerically array. In the associative array, students names as the keys and the value would be their marks. Using a numerically indexed array would not be the best option.
Similarly Index array, the associative array also offers two ways-
-
PHP Multidimensional Array-
We also describe this concept in our YouTube Channel. Watch this on youtube –
PHP multidimensional array can be represented in the form of a matrix and it is represented by rows * columns. It allows you to store data in a tabular form. An array containing one or more arrays and values in the PHP multidimensional array are accessed by using multiple indexes. And each element in the sub-array can be an array and so on. This type of arrays is also known as Array of Arrays. In PHP Multidimensional array each element in the main array can also be an array.
The advantage of PHP Array–
- Less Code: In Arrays, we don’t need to define variables multiple times.
- Easy to traverse: Here, we can traverse all the elements of an array with the help of just a single loop.
- Sorting: Array also gives us a facility of a sorting an elements.