Understanding arrays can be a little difficult in the beginning. But give it a try anyway... we've tried to make it as easy as possible.
What is an array?
An array is a set of indexed elements where each has its own, unique identification number.Sound confusing? It's actually not that complicated.
Imagine a list of words separated by commas. It is called a comma-separated list, and it could, for example, look like this:
Then try to imagine dividing the list at each comma. Next, give each section a unique identification number like this:
What you see is an array. We can, for example, name the array "fruits". The idea is that we can access the array with a number and get a value back, like this:
fruits(0) = apples
fruits(1) = pears
fruits(2) = bananas
fruits(3) = oranges
fruits(4) = lemons
This is the idea behind arrays. Let us try to use it in practice.
How do you use an array?
We will continue with the fruit example. Step by step, we will make it work as a real array. First, we set a variable equal to the list of fruits:Next, we use the function explode to split the list at each comma:
Voila! "$arrFruits" is now an array!
Notice that we called the function explode with two arguments:
- the list that should be split
- and the delimiter - i.e., the character used to split (in this case a comma) - in quotation marks: ",".
Let us try to comment the script and put it into a PHP page:
show example
This example is very simple, and it might be a bit difficult to see the advantage of using an array for this particular task. But just wait... arrays can be used for many very useful things.
Loop through an array
Back in lesson 5 you learned about loops. Now we will look at how you can loop through an array.When you know how many elements an array contains, it is not a problem defining the loop. You simply start with 0 and let the loop continue to the number of items available. In the example with the fruits, you would loop through the array like this:
show example
As you can see, the variable $x (which increases from 0 to 4 in the loop) was used to call the array.
How to find the size of an array
But what if we add another fruit to the list? Then our array will contain one element more - which will get the identification number 5. Do you see the problem? Then we need to change the loop, so it runs from 0 to 5, or else not all of the elements will be included.Wouldn't it be nice if we automatically could find out how many elements an array contains?
That's exactly what we can do with the function foreach. Now we can make a loop that works regardless of the number of elements:
This loop will work regardless of how many or few elements the array contains.
Another example
Below is another example of how you can use an array to write the name of the month:show example
Notice that we use the function array instead of the function explode to create an array.
Ok. Enough about arrays! In the next lesson, you'll learn how to write your own functions.