http://www.developer.com/

Back to article

Arrays in PHP


February 20, 2002

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/";
$Array[]="http://www.internet.com";
$Array[]="http://www.google.com";
$Array[]="http://www.cnn.com/";
$Array[]="http://www.php.net/";

?>


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

$Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com/", "http://www.php.net/");

print $Array[0];

?>


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();
$Array[]="http://www.yahoo.com/";
$Array[]="http://www.internet.com";
$Array[]="http://www.google.com";
$Array[]="http://www.cnn.com/";
$Array[]="http://www.php.net/";

foreach($Array as $key => $value) {
   print "$key: $value<br>";
}
?>


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) {
   
print "$value<br>";
}


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) {
  
if($value == "http://www.yahoo.com") {
     
print strtoupper($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++) {
  
print "$Array[i]<br>";
}

or

$i = 0;
while ($i <= count($Array)) {
  
print "$Array[i]<br>";
 
$i++;
}


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.


Array Functions


PHP includes a range of array-specific functions. These functions can help sort, manipulate, and search for information within arrays. The PHP manual contains a complete list of all the array functions, but let's take a look at a few of the more useful ones now:

in_array()

This function works much like a mini case-insensitive search engine. With it, you can easily see if a value is contained within an array:

<?php

$Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com", "http://www.php.net");

if (in_array("yahoo")) {
   print "Hey! We found yahoo in this array";
}
?>


count()

This function, which determines how many elements are in an array, has already been briefly mentioned:

<?php

$Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com/", "http://www.php.net/");

$num = count($Array);
print $num;
?>


As expected, this would return five.

sort()

One of several different functions to sort arrays, this particular one will sort the elements from lowest to highest (in the case of numerical values) or alphabetically (in the case of string values).

<?php

$Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com", "http://www.php.net");

sort($Array);

for($i=0;$i<count($Array);$i++) {
   
print "$Array[$i]<br>";
}
?>


Since we sorted this array before looping through it, the values will be printed out alphabetically, beginning with http://www.cnn.com and ending with http://www.yahoo.com.

print_r()

Print_r() outputs readable information about a variable. Though not an array-only function, this is actually one of the most useful functions out there when you are working with and debugging arrays. In the case of arrays, it allows you to see every key and the associated value.

<?php

$Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com", "http://www.php.net");

print_r($Array);
?>


This PHP snippet would output: Array ( [0] => http://www.yahoo.com [1] => http://www.internet.com [2] => http://www.google.com [3] => http://www.cnn.com/ [4] => http://www.php.net/ )

If you are trying to visualize what is inside of an array, or trying to track down an error within one, this function is an ideal tool.


Arrays in Action

To demonstrate how you can use arrays in real programming situations, let's write a simple script that pulls a random link from our array of URLs. We will start with the array we have already written:

<?php

$Array=array("http://www.yahoo.com", "http://www.internet.com", "http://www.google.com", "http://www.cnn.com", "http://www.php.net");


Next, we need to get a random entry from the array. To do this, we can use a built-in PHP function that selects a random key from an array:

$random_key=array_rand($Array,1);


The "1" after the array name tells the function that we just want one key to be returned. Now that we have a random key, the final step is to print the associated value out to the browser.

print "<a href=\"$Array[$random_key]\">$Array[$random_key]</a>";
?>


Combine these three sections and save this script as random.php. When you run it from your browser and refresh it, you will see a new URL printed out each time. Adding more items to the array decreases the chances of seeing the same item twice in a row.


Multi-Dimensional Arrays

Let's take a brief look at Multi-Dimensional Arrays. As mentioned before, the most common types of arrays in PHP are the One-Dimensional ones. These are the easiest to work with; however they can only store a single layer of information. In some cases, it's impossible to accomplish what you need to do without being able to store relationships between groups of information. This is where Multi-Dimensional Arrays come into the picture.

Take a look at Figure 2:

This is based on an excerpt from the original array from Figure 1. As you can see, we have added another layer of data. Now, each element within $Array now acts as the parent of another child array.

To create the array illustrated above, you actually nest array functions:

<?php

$Array = array("http://www.yahoo.com" => array("yahoo.gif","yahoo is a directory and a search engine"), "http://www.internet.com" => array("internet.gif","internet.com offers vast resources for web designers and developers");
?>


You could use this array to expand on the concept of a random link generator, and display a banner and a description as well:

<?php

$random_key=array_rand($Array,1);
print "<a href=\"$Array[$random_key]\"><img src=\"$Array[$random_key][0]\"></a> <br>$Array[$random_key][1]";
?>


Assuming you had images within the same directory as the script with the proper names, this script would output that image, linked to the URL, with the description of the link below.

Notice how the elements from the Multi-dimensional array were referenced. From Figure 2, we know that the image name has a key of 0, and the description a key of 1. When we grabbed a random key from the array we had enough information to reference the elements in the child array. When you think of each level of a Multi-Dimensional Array as an array within an array, it becomes easy to see how to manipulate them.

Finally...

In this article, you have been introduced to the concept of Arrays, and learned how to do some essential things like adding and extracting information from them and looping through them.

Arrays are a complex topic, but the more you work with them in real programming situations the easier it becomes to understand how they work, and how to use them. The example random link generator gave you a taste of how useful they can be. In the next article, we will make more use of arrays as we build your first full-fledged application: a form processor.

Stay tuned!


Things to Remember

  • Arrays can be either One-Dimensional, or Two-Dimensional. One-Dimensional arrays are the easiest to work with, but they only can only one layer of information.
  • Every array is made up of elements (the rows of the array), and keys and values within each element.
  • Arrays can be considered either scalar (those with integers as keys) or associative (those with strings as keys).
  • Arrays can be created using the array function or by explicitly setting the values of each element.
  • To extract elements from arrays, you can either reference particular value in the form of $Array[$key] or loop through the array.
  • print_r() is a useful function to help visualize the contents of an array. Using it outputs all the keys and values within an array.

Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.

# # #

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date