In this article I am going to give you a basic primer on Arrays and how we declare, use and manipulate them in PHP. Unlike Scalar Data Types, arrays are a constructs, special variables that contain a collection of other variables which in turn can have varying data types. One way to visualise this would be to think of an Array as a list and inside this list we have empty boxes that can hold or store something. Examine the illustration below featuring the numbered blued boxes to begin with.
Imagine if we wanted to store the letters that spell out the word ‘Arrays’ into each one of these boxes. We would have something that would look like this:
Each letter sits inside a box and and each box has its own number allocated to it. The first Letter in our list which is ‘A’, sits inside box number 0. The second letter in our list which is ‘r’ sits inside box number 1, the third letter which is also a letter ‘r’ sits inside box number 2 and this carries on up till the last letter in our list which is ‘s’ and this sits in box number 5. It could be said that these numbers are identifying each of these letters in our list. For instance, if someone asks what box contains the letter ‘s’ in our list then we would be able to tell them it is number 5. In PHP, we would refer to the box numbers as ‘Keys‘ and the letters as ‘Values‘. The list in our example is the array itself. When the Keys of an array are numbers, we refer to the array as an indexed array. The other term used for indexed arrays is ‘numeric arrays’ but we’ll be referring to these types of arrays as indexed arrays from here on.
You may also refer to the values as the elements of an array but to properly understand this, lets proceed further and discuss variables in PHP for a moment.
As you may already know, we declare variables in PHP like this:
$char1 = 'A';
The above implies we have stored a single character ‘A’, which is of type string, in a variable named $char1. Indeed, we could store the rest of the letters that make up the word ‘Arrays’ into their own variables like follows:
$char2 = 'r';
$char3 = 'r';
$char4 = 'a';
$char5 = 'y';
$char6 = 's';
And then we could concatenate (combine) all these letters and save them in a new variable called $my_array:
$my_array = $char1 . $char2 . $char3 . $char4 . $char5 . $char6;
If we output this onto our screens with an echo statement:
echo $my_array;
OUTPUT:
Arrays
What we just did in the above example is whats known as String concatenation in PHP. We simply combined all the letters that spell word ‘Arrays’ and stored this result into a variable named $my_array.
Interestingly, if we use the PHP function gettype and pass in $my_array as an argument, the return value from this function is string as shown below:
echo gettype($my_array);
OUTPUT:
string
So from the above, you could say that a ‘string’ is nothing but an array of characters itself as its made up one two or more characters. Now shifting our attention back to arrays, how would we go about declaring an array in PHP ?
Creating an Array in PHP (using array() function)
1. We begin with creating a name for our array, which will be a variable name:
$fruits;
2. Next we use an ‘equals’ sign followed by the keyword ‘array’ followed by an opening and closing bracket ‘()’:
$fruits = array();
And that’s it! You’ve declared an empty array named $fruits! There is also an alternative way to create an array in PHP without using the array() function and that is to use the square brackets notation. You can declare an empty array (initialise an array) by creating a variable name for your array followed by the equals sign “=” and then placing an opening and closing square set of brackets like shown below:
$numbers = [];
echo getttype($numbers);
OUTPUT:
array
To pre-initialise an array with a set of values using square brackets notation you would do:
$numbers = [1, 2, 3, 4, 5];
Now in order to get at one of these values you would need to refer to the element by its position, that is, you use its key value as its index. Say we want to get at the 3rd element of our $numbers array, we would simply do the following:
echo $numbers[2];
OUTPUT:
3
As it stands, for the rest of this article we’ll be sticking with the array() function declaration of arrays. Now, if you’re curious about whether ‘$fruits’ really is of type array, now would be a good time to find out. Lets use PHP’s ‘gettype’ method and pass in our array $fruits as an argument:
echo gettype($fruits);
OUTPUT:
array
That’s great. We now have an empty array which we can start populating with values. Lets assume our named array $fruits is a basket in which we wish to place some fresh fruits. The first fruit we want to add into our basket is an apple. How would we do this? Well, we simply enter values within the parenthesis (opening and closing bracket) surrounded by quotation marks as follows:
$fruits = array("apple");
What we have done is we have used the PHP function called array() which creates an array. It takes, as arguments values which can be of any of the supported data types such as string, integer, boolean, float or even other arrays! The below example is also perfectly valid:
$myArray = array("red", 234, "apple", FALSE, 54.256);
Seeing as we have added our first item (apple) into our array, it will now have a Key Value of 0. It is important to stress that when we initialise an array this way, the keys will be created automatically as numbers starting from 0 to n. The first item in an array therefore will always start at index 0:
We can continue to keep adding more items to our array, so lets add another fruit this time we’ll add a banana to our fruit basket:
When the keys of an array are numeric, we refer to this type of array as an indexed array.
Let’s populate our fruits array by passing in more arguments:
$fruits = array("apple", "banana", "orange", "pear");
To see the array as ‘Key / Value’ pairs we can use the PHP function print_r as follows:
print_r($fruits);
When you examine an array variable using print_r, you will get a clean output showing the Keys and their associated Values. Remember, Arrays are simply ‘Key->Value’ pairs. Each Key inside an indexed array will be a number starting from 0 and going to n where n is the last element in your array. Above, you can see the Key ‘0’ holds the value ‘apple’ and its shown as [0] => apple.
Likewise, the Key [1] holds the value ‘banana, the Key [2] holds the value ‘orange’ and finally the Key [3] holds the value ‘pear’.
Another very useful PHP function you can use to examine the contents and structure of an array is var_dump:
var_dump($fruits);
OUTPUT:
array (size=4)
0 => string 'apple' (length=5)
1 => string 'banana' (length=6)
2 => string 'orange' (length=6)
3 => string 'pear' (length=4)
As you can see with var_dump, you get a more detailed output of the array. Alongside the Key value, you are also shown the data type of the associated item being held in the array. Each of our items are of type ‘string’ as shown above. Moreover, you are also presented with information detailing the length of these values in terms of number of characters in each string i.e string ‘apple’ (length=5), meaning apple has a length of 5 characters.
There are three types of Arrays in PHP:
1) Indexed Arrays
2) Associative Arrays
3) Multidimensional Arrays
Accessing Elements of an array
Before I delve into Associative Arrays I want to show you how we access elements of an indexed array, that is, arrays whose Keys are numeric. We can access the elements of an array using the array variable name followed by square brackets containing the key of the item we wish to access. The below example demonstrates how we would output onto the screen the first item of our $fruits array:
echo $fruits[0];
Remember, the first item of an indexed array will always begin at 0, meaning the first item will have a Key value of 0. The above line of code will print the following onto our screen:
OUTPUT:
apple
If we want to print the second item of our array we do:
echo $fruits[1];
OUTPUT:
banana
Likewise if we wanted to print the value of the last item in our array we would do:
echo $fruits[3];
OUTPUT:
pear
Or we could just use a for loop to output all our elements of the $fruits array as follows:
$fruits = array("apple", "banana", "orange", "pear");
for($i = 0; $i < sizeof($fruits); $i++) {
echo $fruits[$i] . “<br />”;
}
OUTPUT:
apple
banana
orange
pear
Changing an elements value inside an array
What if we wished to change the value of one of the items/elements held in our array ?
Lets just say we want to overwrite the value of the last item in our array, which is pear. Well, its easy as using the squared brackets notation and passing in the indices key of that item and then assigning a new value using the equals “=” sign like follows:
$fruits[3] = "peach";
And if we print out the value of the last item we get:
echo $fruits[3];
OUTPUT:
peach
What is an Associative Array?
Earlier we looked at indexed arrays where the keys of the array were numeric. An associative array will differ in that the keys of its array are strings, or simply put, the keys are named keys which you assign to your array items. Below is an example of an associative array:
The above observed as strict PHP Code:
$emp = array(
"Name"=>"Martin",
"Id"=>129, "Age"=>23,
"Dept"=>"Sales",
"Salary"=>35000
);
In an associative array, each item of the array is uniquely identified by its named key. We ‘associate’ the key to its value by using the equals and greater than sign ‘=>’ as shown above. Similarly, to access values of an associative array we use the square brackets notation and place the named key surrounded by parenthesis inside as follows:
echo "Employee Name: " . $emp["Name"];
echo "Employee ID: " . $emp["Id"];
echo "Employee Age: " . $emp["Age"];
echo "Employee Department: " . $emp["Dept"];
echo "Employee Salary: " . $emp["Salary"];
OUTPUT:
Employee Name: Martin
Employee ID: 129
Employee Age: 23
Employee Department: Sales
Employee Salary: 35000
In the above example we have manually accessed and printed out our array values. If you wanted to access them all in one fell swoop, it would be better to use a foreach loop. What a foreach loop allows us to do is access both the keys AND the values of our associative array. The code below demonstrates how this is achieved:
foreach ($emp as $key => $val) {
echo $key . ": " . $val;
}
OUTPUT:
Name: Martin
Id: 129
Age: 23
Dept: Sales
Salary: 35000
To change the value of one of the associative array elements simply use squared brackets notation and add the name of the key whose value you want changed, followed by an equals “=” sign and the new value you wish to assign:
$emp["Name"] = "James";
Lets try to print the new value held in the array element that has the key value “Name”:
echo "Name has been changed to: " . $emp["Name"];
OUTPUT:
James
What is a Multidimensional Array?
In PHP, the third type of array after considering an indexed and associative array is whats known as a Multidimensional array. A Multidimensional array is simply an array containing one or more arrays.
The elements of a multidimensional array are other arrays. Lets imagine we have an array named $nations. Inside this array named $nations, we could declare three more arrays like this:
$nations = array (
array("England", "London", 55.98),
array("France", "Paris", 67.39),
array("Germany", "Berlin", 83.24)
);
What we have here above is an array named $nation which holds elements that are arrays themselves. Just by looking at the above code, we can say that the first item in the $nations is an array which can be represented as: $nations[0]. Likewise, the second item of the $nations array can be represented as $nations[1] and the last item of the $nations array can be identified as $nations[2]. This is great, all we need to do then is echo out all three of these and we’ll see the values of each of these items right? Well lets actually see what happens if we attempt this:
echo $nations[0];
OUTPUT:
Oh dear we have an error message, what happened you’re asking. Well its simple. $nations is our primary array (Level 1 array) and by using the square brackets and using a numerical value, we are trying to get a particular item in this array. However $nations[0] stores an array object, NOT a scalar data type like a normal array value would which we could then print out onto the screen using its key. If $nations[0] held a scalar data type item with a value of string, integer, boolean or float then our echo statement above would have worked fine. However to output the contents of an array whose values themselves are arrays will require a different approach.
The below diagram once again shows you the logical set up of this array and the item we just tried to echo out:
As you can see the first item of our array $nations is an array. This array holds three items which are scalar data types. We already know that to access elements of an array we need to use the square brackets notation along with the relevant key. If the array is an indexed array then its a numeric key. If its an associative array then its a named key. Since the arrays inside of $nations are all indexed arrays, we can refer to them using numeric keys. Equipped with this knowledge then, lets return our attention to the diagram above. If the first item of our array is referred to as $nations[0] this means we are now able to use a second set of square brackets and again apply a numeric key to get at the value we need!
Lets say we want to pull out the value “England” from our $nations array. We can do it like this:
echo $nations[0][0];
OUTPUT:
England
We are saying ‘Find the first item in the array $nations, which is an array itself and from this array hone in on the first item which is the string value “England”. Alternatively, $nations[1][0] would target “France” and $nations[2][0] would target “Germany”. This is how you access values in a multidimensional array where the keys of the parent and child array are numeric, hence these are indexed arrays.
Going back to our previous example, when we looked at associative arrays you may remember we had declared an array named $emp. This array had named key=>value pairs and stored the information of a single employee.
If we wanted to create two more employees this way, we would need to name them in similar fashion, lets say we named them $emp1, $emp2 and $emp3. We would then need to create their own unique values for all the named keys as follows:
$emp1 = array (
"Name"=>"Martin",
"Id"=>129,
"Age"=>23,
"Dept"=>"Sales",
"Salary"=>35000
);
$emp2 = array (
"Name"=>"Gina",
"Id"=>131,
"Age"=>38,
"Dept"=>"Marketing",
"Salary"=>28000
);
$emp3 = array (
"Name"=>"Bhavesh",
"Id"=>129,
"Age"=>26,
"Dept"=>"IT",
"Salary"=>40000
);
Now we have pre-initialized three arrays which contain information about three different employees. The information is stored as Key/Value pairs in each of these three arrays. As it stands , these three arrays are independent of each other and are not related. What if we wanted to have one array that would store all three of these employees as array items? Can this be done ? If so how? Wouldn’t this mean having an array of arrays ? Well, lets have a look what happens when we create an array named $employees and then place these arrays inside of it:
$employees = [
"emp1" => [
"Name" => "Martin",
"Id" => 129,
"Age" => 23,
"Dept" => "Sales",
"Salary" => 35000,
],
"emp2" => [
"Name" => "Gina",
"Id" => 131,
"Age" => 38,
"Dept" => "Marketing",
"Salary" => 28000,
],
"emp3" => [
"Name" => "Bhavesh",
"Id" => 129,
"Age" => 26,
"Dept" => "IT",
"Salary" => 40000,
],
];
We have created a parent array named $employees which holds three items. These three items are arrays themselves, named emp1, emp2 and emp3 respectively. Each of these three arrays are associative arrays whose elements have key / value pairs. Now that we have related all three arrays under one parent array, the below code shows how to access the name of the last employee, which as we can see is ‘Bhavesh’.
echo $employees["emp3"]["Name"];
OUTPUT:
Bhavesh
Exercise for you: What if we wished to obtain all the information on the third employee which is held in the array named “emp3” ?
And finally, if we wish to output ALL the details of EACH employee then the below will suffice:
foreach($employees as $employeeKey => $employeeValue) {
echo $employeeKey;
echo "<br />";
foreach ($employeeValue as $key => $value) {
echo "$key: $value";
echo "<br />";
}
echo "<br />";
}
OUTPUT:
emp1
Name: Martin
Id: 129
Age: 23
Dept: Sales
Salary: 35000
emp2
Name: Gina
Id: 131
Age: 38
Dept: Marketing
Salary: 28000
emp3
Name: Bhavesh
Id: 129
Age: 26
Dept: IT
Salary: 40000
Summary
Hopefully you have enjoyed Part 1 of our Beginners guide to using Arrays in PHP article. In Part 2 we will delve deeper into how we can manipulate and further control arrays using PHP’s built in array functions. Let us wrap up what we have learned in a few points:
- PHP Supports 3 types of arrays: indexed arrays, associative arrays and multidimensional arrays
- With indexed arrays we do not need to explicitly declare the keys, these are created automatically for us when we pass in values to the array() function.
- With indexed arrays, the keys are numeric and the first key will have a value of 0 which references the first item inside the array.
- We can print out the entire contents of an array using PHP’s print_r or var_dump functions. The var_dump function gives us a more detailed output of the contents of an array including the data types of its values.
- We can initialise an empty array with $array = array() or by using the square brackets notation $array = [];
- We can pre-initialise an array with one or more values by passing in our array values as arguments to the array() function
- With associative arrays the keys are named keys and not numeric. These named keys are string data types.
- We can use the foreach loop to traverse through the keys and values of an array.
- All arrays have ‘Key / Value’ pairs.
Sam says
Great article this, lot of concepts explained in a no nonsense easy to follow manner. Looking forward to reading part 2!