4-3: PHP programming language basics – arrays

In the previous section we have seen how to declare a variable in PHP and assign a value to it:

We have focused on strings. However, as other programming languages, PHP supports several types of variables, including of course integers, floating point numbers, boolean values (true/false). See here for a comprehensive overview on variable types in PHP.

Compound types are also supported, including arrays (also called “lists”). What follows is a simple explanation on how to handle arrays in PHP that will fit the needs of this course. You can check the php.net website section on arrays for a more in-depth analysis.

Arrays can be considered a collection of key/values couples.

If we do not explicitly assign the keys, PHP will assign to each element of the array an integer corresponding to it’s position in the array, as key, starting from 0 (not 1!).

Declaring an array

The declaration of an empty array is done as follows:

Let’s consider a classical fruits array:

We now have to learn 2 important skills:

– how to access the various elements of the array
– how to add another element to the array

We can access each element of the array by position. Remember that since we start from 0 rather than 1, the first element has key 0, the second key 1, the third key 2. The syntax to access an element is the the name of the array followed by the key included within square brackets:

Adding an element to an array

In oder to add an element to an array without pre-defined keys (such as $fruits), we use the array name followed by empty square brackets, an equal to operator, and the new element to be assigned. Here is how to add “strawberries” to our $fruits array:

Using var_dump() to check the composition or contents of an array

In the development phase, it can be very useful be be able to somehow quickly check the contents of an array. We can use the var_dump() function to do that. var_dump() will provide information on the structure of an array and the number and type of contained elements.

On executing the code in this example above, you get the following:

First var dump:
array(3) { [0]=> string(6) “apples” [1]=> string(5) “pears” [2]=> string(7) “bananas” }

Second var dump:
array(4) { [0]=> string(6) “apples” [1]=> string(5) “pears” [2]=> string(7) “bananas” [3]=> string(12) “strawberries” }

which is quite easy to read: the array initially comprises 3 elements:


the first ([0]) is a string of 6 characters, apples

[0]=> string(6) “apples”

the second ([1]) a string of 5 characters (pears)

[1]=> string(5) “pears”


the second time we run var_dump on the array, there are 4 elements


because we did add the strawberries.

So remember that during the code development phase, if you want to know how an array is composed, you can run var_dump() on it.

Iterating through all the elements of an array: the foreach cycle

As in other programming languages, in PHP there are several ways we can iterate, or go through all the elements of an array, one by one, and do something.

foreach(), while(), for() are functions that allow us to do that. Depending on the situation, one way of iterating could be more convenient than others. Here we will show how to use the foreach() method, which is quite straightforward and will fit most situations. It does exactly what the name, foreach, implies: for each element of the array, do something. The foreach() syntax is explained below.

In order to write a foreach cycle, we suggest you first write down an “empty” foreach structure, and then fill it up with your contents. Doing so will ensure you do not forget any brackets. In our experience, it is indeed not uncommon for inexperienced or beginners coders to forget for instance the last closing bracket of the construct.

The empty structure look like this:



Here is how we can cycle through our $fruits array:

on running this code and visiting the script page with the browser you will this:


if you look at the source code, you will see:

if you want to generate a more tidy source code, with each element, in the source code, on it’s own line, you could explicitly insert a newline character (backslash n, \n) after each break tag:

On visiting this page, the result is identical to the one you get with the previous example. However if you view the source code of the page, you will now see:

which make it more readable. In this simple example the difference is maybe not so relevant, but there are instances is which having a nicely readable HTML source code can make code development easier.

So consider, every time you output a break tag or close a paragraph tag, or other tags, to follow with a \n so as to generate a newline in the HTML source code.

Back to the foreach() syntax, our example begins with:

foreach($fruits as $fruit)

this means that each time we consider one element of the $fruits array, during the cycle,

foreach($fruits as $fruit)

we can access/manipulate it by referring to it as $fruit within the curly brackets {} that follow.

foreach($fruits as $fruit)

While in the first part, we indeed have to use the name of the array, as previously defined in the code ($fruits), on which we wish to cycle, how we want to call the elements while we consider them, on by one, during the iteration (what we do with them within the curly brackets), is arbitrary and entirely up to us. It is however typical, and a good idea for code readability, to select a name that makes sense and reflects the nature of the elements of the array. In this case, indeed, each element is a fruit (singular), so it makes a lot of sense to use the variable name $fruit. However each one of those would be entirely valid:

foreach($fruits as $a)

foreach($fruits as $tool)

foreach($fruits as $asdfgh)

foreach($fruits as $whatever)

If you want to make your life more difficult, or make the code harder to understand, you could indeed do that. We recommend, though, that you use variable names that do make sense for the context. This is actually a general recommendation that holds true for all the variable names that you create in your code, it is one of the so-called “good programming practices” that make the difference between a poor coder and a great coder.

Consider the following other examples, which all make a lot of sense with respect to the choice of the variables names:

It is typical to use a plural for the name of the array ($fruits) and the corresponding singular for the name of the individual items to use in a cycle ($fruit).

How to declare and manipulate an array with keys

So far we have considered examples of arrays in which the keys were not explicitly declared, so that the items can be accessed by using integers that reflect their position inside the array, starting from 0.

Let’s now see just one example of an array explicitly declared with keys instead. Here is the syntax:

The array in the example above, called $complement_dict (for complement dictionary), have 4 keys available, made in this case by single characters, all uppercase: A, T, G and C. You may recognise the nucleotides or bases that can be found in DNA. The value for each of the keys is the base that, given a strand of DNA, you would find on the opposite strand, also known as the complementary base or “complement”. This key-based array, also know as a “dictionary”, is quite handy in finding out, given a nucleotide, it’s complementary nucleotide. We will use it extensively, with some variations, in some of the web applications examples in this book later on.

For now, let us just briefly consider these code examples that highlight how to declare, manipulate and access elements in an array with keys.

Chapter Sections

Leave a Reply

Your email address will not be published. Required fields are marked *