Home arrow PHP arrow Page 2 - Arrays

Outputting Arrays - PHP

Arrays offer an ideal means for storing, manipulating, sorting, and retrieving the kinds of data sets that programmers spend a lot of time working with. PHP supports the array data type. This article explains the array-based features and functions it supports. It is excerpted from the book, Beginning PHP 5 and MySQL: From Novice to Professional, by W. Jason Gilmore (Apress, 2004; ISBN: 1893115518).

TABLE OF CONTENTS:
  1. Arrays
  2. Outputting Arrays
  3. Testing for an array
  4. Locating Array Elements
  5. Determining Array Size and Uniqueness
  6. Other Useful Array Functions
By: Apress Publishing
Rating: starstarstarstarstar / 37
June 23, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Although it might not necessarily make sense to learn how to output an array before even knowing how to create one in PHP, this function is so heavily used throughout this chapter, and indeed, throughout you daily programming life, that it merits first mention in this chapter.

print_r()

boolean print_r(mixed variable [, boolean return])

The print_r() function takes as input any variable and sends its contents to standard output, returning TRUE on success and FALSE otherwise. This in itself isnít particularly exciting, until you take into account that it will organize array contents (as well as an objectís) into a very readable format before displaying them. For example, suppose you wanted to view the contents of an associative array consisting of states and their corresponding state capitals. You could call print_r() like this:

print_r($states);

This returns the following:

Array ( [Ohio] => Columbus [Iowa] => Des Moines [Arizona] => Phoenix )

The optional parameter return modifies the functionís behavior, causing it to return the output to the caller, rather than sending it to standard output. Therefore, if you want to return the contents of the above $states array, you just set return to TRUE:

$stateCapitals = print_r($states, TRUE);

This function is used repeatedly throughout this chapter as a simple means for displaying the results of the example at hand.

TIP The print_r() function isnít the only way to output an array, but rather offers a convenient means for doing so.Youíre free to output arrays using a looping conditional (such as while or for), and in fact these sorts of loops are required to implement many application features. Iíll come back to this method repeatedly throughout not only this chapter, but also throughout the entire book.

Creating an Array

Unlike other, much more annoying array implementations of other languages, PHP doesnít require that you assign a size to an array at creation time. In fact, because itís a loosely-typed language, PHP doesnít even require that you declare the array before you use it. Despite the lack of restriction, PHP offers both a formalized and informal array declaration methodology. Each has its advantages, and both are worth learning. Weíll examine both in this section, starting with the informal variety.

You reference the individual elements of a PHP array by denoting the element between a pair of square brackets. Because there is no size limitation on the array, you can create the array simply by making reference to it, like this:

$state[0] = "Delaware";

You could then display the first element of the array $state like this:

echo $state[0];

You can then add additional values by referencing the intended value in conjunction with the array index, like this:

$state[1] = "Pennsylvania"; 
$state[2] = "New Jersey";
...
$state[49] = "Hawaii";

Interestingly, if you assume the index value is numerical and ascending, you can choose to omit the index value at creation time:

$state[] = "Pennsylvania";
$state[] = "New Jersey";
...
$state[] = "Hawaii";

Creating associative arrays in this fashion is equally trivial, except that the associative index reference is always required. The following example creates an array that matches U.S. state names with their date of entry into the Union:

$state["Delaware"] = "December 7, 1787";
$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
...
$state["Hawaii"] = "August 21, 1959";

Next Iíll discuss a functionally identical, yet somewhat more formal means for creating arrays: via the array() function.

array()

array array([item1 [,item2 ... [,itemN]]])

The array() function takes as its input zero or more items and returns an array consisting of these input elements. Here is an example of using array() to create an indexed array:

$languages = array ("English", "Gaelic", "Spanish");
// $languages[0] = "English", $languages[1] = "Gaelic", $languages[2] = "Spanish"

You can also use array() to create an associative array, like this:

$languages = array ("Spain" => "Spanish",
                   "Ireland" => "Gaelic",
                   "United States" => "English");
// $languages["Spain"] = "Spanish"
// $languages["Ireland"] = "Gaelic"
// $languages["United States"] = "English"

list()

void list(mixed...)

The list() function is similar to array(), though itís used to make simultaneous variable assignments from values extracted from an array in just one operation. This construct can be particularly useful when youíre extracting information from a database or file. For example, suppose you wanted to format and output information read from a text file. Each line of the file contains user information, including name, occupation, and favorite color, with each piece of information delimited by a vertical bar ( | ). A typical line would look similar to the following:

Nino Sanzi|Professional Golfer|green

Using list(), a simple loop could read each line, assign each piece of data to a variable, and format and display the data as needed. Hereís how you could use list() to make multiple variable assignments simultaneously:

// While the EOF hasn't been reached, get next line
while ($line = fgets ($user_file, 4096)) {
     // use explode() to separate each piece of data.
     list ($name, $occupation, $color) = explode ("|", 
     $line);
     // format and output the data
     print "Name: $name <br />";
     print "Occupation: $occupation <br />";
     print "Favorite color: $color <br />";
{

Each line would in turn be read and formatted similar to this:

====================================================
Name: Nino Sanzi
Occupation: Professional Golfer
Favorite Color: green ====================================================

Reviewing the example, list() depends on the function explode()to split each line into three elements, which in turn uses the vertical bar as the element delimiter. The explode() function is formally introduced in Chapter 9. These elements are then assigned to $name, $occupation, and $color. At that point, itís just a matter of format- ting for display to the browser.

range()

array range(int low, int high [,int step])

The range() function provides an easy way to quickly create and fill an array consisting of a range of low and high integer values. An array containing all integer values in this range is returned. As an example, suppose you need an array consisting of all possible face values of a die:

$die = range(0,6);
// Same as specifying $die = array(0,1,2,3,4,5,6)

The optional step parameter offers a convenient means for determining the increment between members of the range. For example, if you want an array consisting of all even values between 0 and 20, you could use an step value of 2:

$even = range(0,20,2);
// $even = array(0,2,4,6,8,10,12,14,16,18,20);

The range() function can also be used for character sequences. For example, suppose you wanted to create an array consisting of the letters A through F:

$letters = range("A","F");
// $letters = array("A,","B","C","D","E","F");



 
 
>>> More PHP Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: