Go to the menu - Go to the contents

[Site map] You are here --- > Newbies Paradise > Tutorials > Official > Website > Reading a tutorial

Arrays

Avatar
Author : M@teo21
Creation : : on 08/23/2007 03:52:54 PM
Last modification: : on 08/23/2007 05:25:10 PM
Rate and comment this tutorial
Print this tutorial
This is a very important chapter in PHP: arrays. Arrays are complex variables which store a group of values under a single variable and can be compared to a table.
Arrays can be used to do several things and they are not easy to use all the time. A PHP expert will easily recognize in this chapter the "basics of PHP".
It may seem repetitive but this chapter is really important and if you understand it then you will not have problems understanding the chapter on data bases in the second part of this tutorial.

Because I don't want to complicate things, I have decided to separate this chapter in 2 parts: In this chapter we are going to learn the minimum to understand arrays, an then in part III of the tutorial we are going to use them thoroughly.
Now let's get down to the real thing :pirate:
Chapter Contents :
Previous Chapter Contents

Indexed arrays

what is exactly an array?

An array is a special type of variable.

You've been working so far on simple variables i.e. having a name and a value, for instance:

Code: PHP
1
2
3
4
<?php
$firstName = "Nicole";
echo "Hi $firstName!"; // output : Hi Nicole !
?>

We can put it like this:

Name Value
$firstName Nicole

It is also possible to store as much information as you want in an array. Take a look at the following table.

Number Value
0 Francis
1 Mike
2 Nicole
3 Veronica
4 Ben
... ...

$firstName is an array : we call that an "array" variable with not only one value but several values (you can put as many values as you want).
In an array, values are sorted in different cells. In our example we work on an indexed array.


PHP assigns the numbers automatically but it's important to note that the numbering always starts by 0! Failing to do so may lead to errors

To display Veronica for instance, you need to use display $firstName in cell 3 because if you just use $firstName, PHP does not know which name to display:


well! How does it work in practical terms? :huh:
You have to write the variable's name followed by the number between brackets like in the following example:


Code: PHP
1
2
3
<?php
echo $firstName[3];
?>

It seems too simplistic :) but if you forget to put the brackets it won't work.(You get back "Array"...) You are obliged to use brackets to indicate the cell where to get the information.

How do you create an array?
Creating an array is a bit particular because you have to use array functions and this is what we are going to see in the following example.

Code: PHP
1
2
3
4
<?php
// the array fucntion is used to create an array
$firstNames = array ("Francis", "Mike", "Nicole", "Veronica", "Ben");
?>

The order of words is very important. The first element ("Francis") is assigned n°0, followed by Mike n°1 etc etc...
And it's just as simple as that. You know how to create an array and how to display the content of the cell.

To sum up this chapter, we can write a small script to display the content of our $firstNames array.
We start by creating an array as what we did above and then use a while or for loop but preferably a for loop.

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
// We create our  $firstNames array
$firstNames= array ("Francis", "Mike", "Nicole", "Veronica", "Ben");
 
// use a loop to display the output :
for ($number = 0; $number < 5; $number++)
{
    echo $firstNames[$number]; // display $firstNames[0], $firstNames[1] etc...
    echo "<br />"; // beginning of the line
}
?>




It's Wonderful, isn't it ? :magicien:

Associative arrays

This part is similar to the above one but instead of using a number as a key, we use a word.
If for instance we want to sort the details of a person in an array (name, address, town etc.) we are not going to use numbers but words as key.

Associative arrays are very important and to create them we are going to use the array function but with a key in front of each detail:

Code: PHP
1
2
3
4
5
6
7
8
<?php
// we create our array $details
$details = array (
    "First name" => "Francis",
    "Last name" => "Dupont",
    "Address" => "Paradise street",
    "city" => "Manchester");
?>


Note that there is only one statement (one semicolon). I could have written all on a single line but I cut it in several lines which I think is easier to read. :)


You can notice an arrow(=>) which stands for associated to. For instance "town associated to Marseille".

How do we display the content of the array

Well, we procede as what we did before, by using brackets with apostrophes inside. Using apostrophes is not compulsory but it's a good habit you can take.

Look at the following example.

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
// We create the associative array :
$details = array (
    "First name" => "Francis",
    "Last name" => "Dupont",
    "Address" => "Paradise street",
    "City" => "Manchester");
 
// To display the city :
echo $details['city'];
?>




Associative arrays are very important for the second part of this tutorial because you need them when working on database.

Quiz

What is an array
Which number starts an indexed array ?
What does this code display ?Code: PHP - Show / hide line numbering
  1. <?php
  2. $firstnames = array ("Francis", "Mike", "Nicol", "Veronica", "Ben");
  3. echo $firstnames;
  4. ?>
How many different types of informations can we put in an array
A small mental calculation: What is the value of $result?Code: PHP - Show / hide line numbering
  1. <?php
  2. $numbers = array (4, 6, 2, 9, -1, 7);
  3. $result = ($numbers[2] * $numbers[4] + $numbers[0]) / ($numbers[1] - $numbers[0]);
  4. ?>
A small practical. We store the prices of some articles in an array and we calculate the total price. What's the value of $total ?Code: PHP - Show / hide line numbering
  1. <?php
  2. $price = array (
  3.     "Egg" => 1.5,
  4.     "Orange" => 0.5,
  5.     "Chips" => 2
  6. );
  7. $total = (2 * $price['Egg']) + (1 * $price['Chips']) + (4 * $price['Orange']);
  8. ?>


This is the end of the first part I !!! :D
Maybe you don't notice it for now but let me tell you have learned a lot of things. The beginning is always the hardest part, but you've made it so congratulations!

The next chapters will seem easier and agreable to read. you are on the good way so keep on learning and you will soon become PHP professionnals
Previous Chapter Contents
Author : M@teo21
Rate and comment this tutorial
Print this tutorial

Change your template | Learn more about NP | Site map | Terms of use | Rules | RSS feed | XHTML 1.0 | CSS 2.0
Powered by Simple IT SARL: Contact us

There is nothing else to read, you have to go up now !

Do you want to be published here? Contact us.

Number of Newbies connected 6 Newbies Connected | SQL requests 10 Requests | Page loading delay 0.18s (0.1694s)