Make your own free website on Tripod.com

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Creating List Arrays

To create an array we make use of the array() function thus:

$arrayName = array();

In this case $arrayName is a name I have decided to give my array. It is a variable name (only it has several rooms) and must therefore adhere to the rules for creating variables which are:

  1. an array's name MUST start with a dollar sign ($)
  2. the first character after the dollar sign MUST be an alphabetic digit or underscore
  3. the remaining characters in an array's name can ONLY be made up of alphanumeric characters or the underscrore
  4. an array's name MUST NOT contain spaces

The code therefore simply creates an empty array called $arrayName.

It is also possible to create an array and fill it with values straight array. Supposing we wanted to create an array to hold names of different fruits, we would code:

$fruits = array("oranges","mangoes","pawpaws");

...this creates a new array called $fruits that now contains values and looks something like this:

012
orangesmangoespawpaws

To print any of the values, you simply refer to it's 'room number' (counting from zero) eg.

print "$fruits[0]\n";
print  $fruits[2];

Refering to our array created above, this will print:

oranges
pawpaws

This is because the first item in our array is "oranges" (room 0), followed by mangoes(room 1)... So printing $fruits[0] prints the first item from the array while $fruits[2] prints "pawpaws" - the item in room 2, the third room. Smart eh?!

Take note of the \n. This as you will remember is a newline character causing the carriage return (also called Enter) to be printed. Of course your browser is very good at ignoring newline characters - that is why we use the P tag and not the newline.

What if you wanted to add an item to an array?

<< PHP Arrays | Adding Items to an Array >>

JamHitz Productions