PHP
  Home arrow PHP arrow Page 2 - Arrays
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Arrays
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 36
    2005-06-23

    Table of Contents:
  • Arrays
  • Outputting Arrays
  • Testing for an array
  • Locating Array Elements
  • Determining Array Size and Uniqueness
  • Other Useful Array Functions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Arrays - Outputting Arrays


    (Page 2 of 6 )

    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


       · The writer forgot something important. Not only does array_pop return the last...
       · The capital of Nebraska, used in the example, is Lincoln (not Omaha).
     

    Buy this book now. This article is excerpted from the book Beginning PHP 5 and MySQL: From Novice to Professional, by W. Jason Gilmore (Apress, 2004; ISBN: 1893115518). Check it out at your favorite bookstore today. Buy this book now.

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT