1. Introduction
An array stores multiple values of similar types in one single variable. Assume a scenario in which you want to store names of all the planets in our solar system. To store them you will need eight variables and your program will look bad. Now assume that you need to store all planets in milky way – that’s around billions. To store all the planets in our milky way, we cannot create billions of variables. To solve similar scenarios, we make use of arrays. Let’s see how we can use them.
2. Creating and accessing an array
Arrays are created with elements listed in []
. We can declare arrays as:
$planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Neptune','Pluto'];
In above code, $planets
is an array having 8 elements. In arrays, element position starts from 0. Mercury gets stored at position 0, Venus at position 1, Earth at 2 and so on. Formally, we call places as “keys” and value as “value”.
Now assume, you want to access the element present at position 6, you can access it as:
echo $plantets[6] // prints Neptune
To print all the content of a array, you can use print_r
function:
print_r($planets);
3. Storage of arrays in memory
Arrays are stored in an continuous location in memory. We can visualise it as continuous storage of key-value pairs of array. It can be visualised as:
4. Indexed arrays
Indexed arrays use numbers starting from 0 as their key. These are default type of arrays in PHP. The $planets array that we created earlier is an indexed array as its keys start from 0.
5. Associative arrays
Associative arrays use named keys that we assign to them. Assume we want to store salaries of employees as keys with name of employees:
$salaries = ["Gaurav"=>"35000", "Shivam"=>"37000", "Chanchal"=>"43000"];
To look for the salary of Chanchal we can do:
echo $salaries['Chanchal']; // prints 43000
6. Multidimensional arrays
By dimension of array we simply mean number of keys used. Sometimes we want to more than one information. Assume that you want to store department, name and salary of an employee. For same, we can store department on first place, name on second place, salary on third place and take it as array. And then we can make array of these array. So, it would be a 2-dimensional or 2D array:
$information = [ ["Gaurav","Technology",35000], ["Shivam","Marketing",37000], ["Ashutosh","Leadership",""], ["Rahul","Leadership",45000] ];
7. Conclusion
In this post we learned about arrays, how and where we should use them. We also discussed about different types of arrays. In the next blog post of this series, we will learn about strings in PHP. Till then, we will have a solid grasp on all the concepts that we discussed in this series.