Creating an Array

I l @ ve RuBoard

The formal method of creating an array is to use array(), the syntax of which is:

 $List = array ("apples", "bananas", "oranges"); 

In this examplewhere you have not specified an index for the elementsthe first item, apples, will automatically be indexed at 0, the second at 1, and the third at 2. You can assign the index when using array() as follows :

 $List = array (1=>"apples", 2=>"bananas", 3=>"oranges"); 

The index value you specify does not have to be a number, you could use words as well. This technique of indexing is very practical for making more meaningful lists. As an example, you could create an array which records the soup of the day for each day of the week.

Script 7.1. This is another example where adding white space to the page in order to clarify your programming (when initializing the array) won't have any adverse affects and is therefore recommended.

graphics/07sc01.jpg

To create an array:

  1. Create a new PHP document in your text editor.

  2. Write the standard HTML header (Script 7.1).

     <HTML><HEAD><TITLE>Using Arrays </TITLE><BODY> 
  3. Begin the PHP section of the script and use the array() function to create an array.

     <?php $Soups = array( "Monday"=>"Clam Chowder", "Tuesday"=>"White Chicken Chili", "Wednesday"=>"Vegetarian" ); 

    This is the proper format for initializing (creating and assigning a value to) an array in PHP, using strings as the indices.

  4. Print the array to the Web browser.

     print ("$Soups<P>\n"); 
  5. Close the PHP and the HTML.

     ?></BODY></HTML> 
  6. Save your document as soups.php, upload it to your server, and test in your Web browser (Figure 7.3).

    Figure 7.3. Because an array is structured differently than other variable types, a request to print an array will result in the word array being printed. While printing that is not as useful as printing out the individual values of the array (as you'll learn to do), it does confirm for you that the array was successfully created.

    graphics/07fig03.gif

Tip

The practice of beginning any index at zero is standard in PHP and most other programming languages. As unnatural as it may seem, it's here to stay, so you have two possible coping techniques. First, manually start all of your arrays indexed at the position 1. Second, unlearn a lifetime of counting from one. You can decide which is easier but most programmers just get used to this odd construct.


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net