July 25, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Arrays in PHP

  • February 20, 2002
  • By Elizabeth Fulghum
  • Send Email »
  • More Articles »


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.

# # #





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel