FFD - Visit the site
ICMS

28 January 06

Beginner PHP Tutorial 5: Looping and Arrays

This tutorial will explain exactly what arrays are, when they should be used and how they are used in php. I will then describe how to create loops, which can be used with arrays.

Array? What’s that?

Arrays are very powerful, I mean very very powerful. They are like tables, storing not just one bit of data (or one row), but lots of bits of data (two or more rows). Each bit of data is assigned an identification code (or an id) which is used to store the data in the correct place in an array, and to obtain the correct data from the array.

They are two types of identification codes: string or numbers. Both can be used within an array in php, but are different in the way they are handled. A string is simply some text which is linked to the data. So the “version” id n an array could be linked to “2.0”, but later the “version” id could be used to change the version to “2.1”. A numerical identification code is actually compared to other numbers. So, usually, an array starts at 0 (not one, zero) and goes up from there. In php there is an easy syntax to add a new numerical id to an array.

In some programming languages, there are limits to array lengths (based on what you set to start off), but conveniently in php there is no limit. So you don’t have to predict how many values could be in your array, now that is nice, isn’t it?

I figure you probably still don’t understand so I will give a little example before going onto the next section of this tutorial.

IdValue
0Hello, this is data
1Goodbye, this is data
2Wow, this is data
no_wayNo way, this is data

The above table clearly shows there are two columns. This table is like an array, with an id column and a value column. You tell php the id of some data in an array, and then php find the id, and returns the data alongside. PHP does the same sort of thing if you want to change some data, it just changes the value to what you specify.

Hopefully, you now understand. If not, feel free to contact me (click the contact tab above).

When would I use an array?

Very often, actually. In a big project, you simply can’t avoid them, they are everywhere, but that’s not a bad thing. A typical example of an array in use is when data is returned from a database/table. Without an array, the task of sorting the data and showing it correctly would be impossible (unless you used variable variables, which I will explain in a later tutorial). The array can be used to store all of the information, and link it together, without overwriting variables already existing.

Another example is when a folder is opened and analysed for files. The names of the files/folders found and their type (html, php, folder, css, javascript, image?) would be stored in an array. The data could then be run through to produce valid results to the user.

Arrays in PHP

In PHP arrays are variables, which have some special functionality. To define an array, although it is usually not necessary, you use:

<?php
$array = array();
?>

Within the array() function you can also insert some data into the new array:

<?php
$array = array('a', 'b', 'c');
?>

This assigns numerical values to each bit of data. So the id of ‘a’ is 0 and the id of ‘b’ is 1. You can assign string ids with:

<?php
$array = array('first' => 'a', 'second' => 'b', 'third' => 'c');
?>

This means that ‘a’ has an id of ‘first’ and ‘b’ has an id of ‘second’.

Now you have created your array you can access data of an array placing the id within the square brackets [ and ] :

<?php
echo $array [0];
?>

You can also assign data with this same format:

<?php
$array [0] = 'A';
?>

If the data relating to the id in the array doesn’t exist, it is created. If it does exist it is overwritten.

You can have arrays in arrays, so the following is completely fine:

<?php
$array = array();
$array [0] = array();
$array [0]['first'] = 'A';
?>

Note the use of the string instead of a number.

To get an analysis of an array, you will probably want to use the function print_r($array) :

<?php
$array = array();
$array [0] = array();
$array [0]['first'] = 'A';
print_r($array);
?>

This will print an analysis of the array of the screen.

Another useful function is count() which returns the number of id values in an array:

<?php
$array = array();
$array [0] = 'a';
$array [1] = 'b';
echo count($array); //should return 2
?>

Finally, you can also automatically add a piece of data with a non existing numerical id by using [] :

<?php
$array = array();
$array [] = 'A';
print_r($array);
?>

This makes $array [0] equal to ‘A’, because it is the first unused numerical id within the array.

NOTE: A space should not be placed between the array variable and the square brackets. I have only put this in my code because otherwise the formatting tool I use for this website incorrectly converts the square brackets into html.

Loops

Loops are really simple, they are bits of code which are repeated n number of times (n is defined by your script). Well, the most common loop, “for” works in this way, but there are some others, with different ways of working. I will start with for() though. An example of a for() loop is:

<?php
for($i=0; $i<10; $i++){
   echo $i.' ';
}
?>

This will output the numbers 0 to 9, with spaces in between them, and a space at the end. The for loop executes the code within it when the second parameter is true (like an if function). The first parameter is ’$i=0’ in this case, and is what happens when the loop is started. Then, each time the loop is started, the second parameter is evaluated as a condition. If it is true then the loop continues, otherwise, it ends. At the end of each loop the third parameter is executed.

In the example the variable $i is created at the start with a value of 0. $i is indeed less than 10 so it does the loop, echoing $i. Then it reaches the end of the first loop and makes $i one larger. When this process has repeated enough times, the loop is ended because $i is no longer less than 10 (as instructed in the second parameter).

The next function is while(), which is a simpler function, but still very similar. Here is the same example using while():

<?php
$i = 0;
while($i<10){
   echo $i.' ';
   $i++;
}
?>

Note: If you didn’t know, $var++ adds 1 to the value of of $var.

As you can see, while is pretty much the same, although leaves more up to the script. You have to define $i seperately, while won’t do it for you. While() can be useful however, when you want to continuously call a function, and execute some code until that function returns false. A common function like this is mysql_fetch_object() (or mysql_fetch_array()), which I will teach you in a later tutorial along with mysql.

The next type of loop is actually very different, foreach(). This function is designed to run through the contents of an array, and execute code for each id. The code is also handed the id and value of the current section of the array it is on. Here is an example:

<?php
$array = array('a', 'b', 'c', 'd');
foreach($array as $id => $value){
  echo $id.' => '.$value.', ';
}
?>

To use the function you must first provide the array variable, then the keyword ‘as’ and then the name of the variable you want to hold the value for each “row” or “section” of the array. As I have done in my example, you can also have a variable for the id, which must be between the ‘as’ and the value variable. It must also end with ’=>’, so php understands it as the id and not the value.

All done? Really?

Yes, that is the end of this tutorial. I really do recommend that you read this through at least more than once, and make sure that you understand the key concepts. If you don’t understand anything after two or more reads, then feel free to contact me (using the contact tab above). Once you have done that, you are ready to move onto the next tutorial.

By the way, well done on your hard work, you are well on the way to being a php coding genius now!