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  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

Arrays
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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
     

       

    PHP ARTICLES

    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek