Arrays in PHP
Arrays fall under the same category that a lot of concepts in PHP do: "Difficult to understand at first, easy to use once you do, and impossible to live without."
In this article, we will be taking a look at why they are so important to program development, and explore how to work with them. You will also learn how you can write a random link generator using arrays, and expand it to display banners or buttons associated with the links.
So, What Exactly are Arrays?
Arrays, common
to almost every programming language in one form or another, are a data type
which allows groups of related data to be stored in a structured table-like
format. Simple arrays look a lot like a database or spreadsheet from your
favorite office suite, and can be manipulated in much the same way.
In PHP, an array is assigned to a single variable, but it can hold dozens of
individual pieces of information. Each individual bit of information, or row,
is referred to as an array element. Within every array element there
are two parts: the value, which contains the actual information you want
to store, and a unique key which identifies the value. You'll learn later
how keys play an important role in the process of accessing and manipulate array
elements.
Keys can either
be non-negative integers, or strings. Arrays with integers as keys are the
most common types and known as Scalar Arrays. Those with strings as keys are
called Associative Arrays.
If you were to visualize an Array, it would look something like the example
in Figure 1.

This array is called $Array. It has 5 values, and is considered a scalar array because the keys are integers.
It would also be classified as a One-Dimensional Array, because it holds only a single layer of information. PHP includes supports Multi-Dimensional Arrays as well, which allow you to have multiple layers of information. We will touch on Multi-Dimensional Arrays a later on in the article, but for now, let's keep it simple.
Creating and Populating Arrays
Arrays are created using the array
function:
| <?php
$Array = array(); print $Array; ?> |
When this script is run, you will see that the only output is "Array". Since
an array is merely a container for data, any time you try to print out a variable
with an array assigned to it without referencing a particular element, PHP outputs
"Array".
So far, our array does not anything in it, so let's take a look at some of the
different ways you can add data to it.
The first way to add elements is
by passing them to the array function:
| <?php $Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com/","http://www.php.net/"); ?> |
Notice that we did not assign any keys for the values. You have the option of
leaving the keys out -- in which case PHP will automatically assign numerical
ones -- or explicitly setting them.
Its important to remember that when you allow PHP to set the keys, the first element will always be assigned an index of 0, not 1. If you already have some keys specified, PHP will assign the next highest integer to act as the key for the values not assigned:
| <?php $Array=array(1 => "http://www.yahoo.com", 2 => "http://www.internet.com", 3 => "http://www.google.com", "http://www.cnn.com/", "http://www.php.net/"); ?> |
You can also assign string values
as keys in much the same manner:
| <?php $Array=array("yahoo" => "http://www.yahoo.com", "internet" => "http://www.internet.com", "google" => "http://www.google.com", "cnn" => "http://www.cnn.com/", "php" => "http://www.php.net/"); ?> |
The second way to assign values is to explicitly set them. In addition to being
used to initially populate an array, this method can also be used at any time
to add new elements to an existing array, or alter an existing element by setting
a new value. Including the new array statement is optional, as PHP will automatically
create the new array if it doesnt exist when you try to add elements:
|
<?php $Array = array(); $Array[]="http://www.yahoo.com/"; |
Again, these values have been added without explicitly declaring a key for them,
but you can easily assign numerical or associative keys:
|
$Array[1]="http://www.yahoo.com"; or $Array["yahoo"]="http://www.yahoo.com"; |
Which method you use on a daily basis
is largely up to personal preference; however, the second method has the benefit
of being slightly more readable when working with long pieces of data.
Outputting Elements from Arrays
So, now that we have data in the
array, how do we access it? This is where keys begin to play an important role.
Looking at Figure 1, and remembering that PHP automatically assigned key to
this array (beginning with 0), it's easy to access a specific array value using
its index. Try the following script:
|
<?php ?> |
Since we are accessing the array
stored in the variable called $Array, and the element assigned to the key with
a value of "0" is specified, this script outputs "http://www.yahoo.com".
If you wanted to print out every element in the array, you could do it by specifically referencing the key for each one like this:
|
print "$Array[0] $Array[1] $Array[2] $Array[3] $Array[4]"; |
But as you can see, it would quickly get cumbersome if you had a more than a
few elements.
To make things easier, PHP also allows you to iterate through arrays using loops. The foreach loop is specifically designed to work with arrays:
|
<?php $Array = array(); foreach($Array as $key
=> $value) { |
The loop advances an internal pointer through each row of the array, assigns the key and the value to variables, and then prints out one or both of them until the end of the array is reached.
In this example, every key and value in the array would be outputted to the browser, but if you did not need to use the key of the array for anything, you could simplify the loop even further:
|
foreach($Array as $value)
{ |
Within the foreach loop, you can
easily perform operations on the array elements and include other control structures
to drilldown to the information you want:
|
foreach($Array as $value)
{ |
In the above example, nothing would
be printed out until the value of an element within the array was equivalent
to "http://www.yahoo.com". At that point, the $value would be capitalized using
strtoupper() and printed out.
A foreach is not the only way to
move through an array. If you have a scalar array indexed automatically or manually,
without gaps, you could also use a for or while loop to move through the array:
|
for($i=0;$i<=count($Array);$i++)
{ or $i = 0; |
These two snippets essential do the
same thing: beginning with a count of 0, print out the array element with the
key equal to the value of $i, increase the value of $i, and repeat. This continues
until $i is equal to the number of elements within the array, which is found
by using count($Array);
As you can see, these two methods are a little more verbose than using a foreach loop, but they are both perfectly acceptable methods in most situations.
