Arrays


 $array[index] = value; $array = array(value1, value2); $array = array(key1 => value1, key2 => value2); 

Arrays are indexed collections of data items, starting by default with an index of 0. You can create arrays by assigning data to them, and you can give arrays the same names as you give to standard variables. Like variable names, array names begin with a $. PHP knows you're working with an array if you include [] after the name, like this:

 $array[1] = "No worries."; 

This creates an array named $array and sets the element at index 1 to "No worries.". From now on, you can refer to this element as you would any simple variableyou just include the index value to make sure you reference the data you want, like this:

 echo $array[1]; 

This statement would echo "No worries.". This example stored a string using a numeric index, but you can also use string indexes. Here's an example of using string indexes:

 $data["Ralph"] = 123; $data["Tom"] = 567; $data["Ted"] = 980; 

You can now refer to the values in this array by string, as $data["Ralph"], and so on.

You can also use a shortcut for creating arraysyou can simply use [] after the array's name, and PHP increments the array's index as you add new elements; the created index values will be numeric. Here's an example:

 $data[] = 123; $data[] = "Hello"; $data[] = "Good day"; 

In this case, $data[0] will hold 123, $data[1] will hold "Hello", and $data[2] will hold "Good day".

Here's an even shorter shortcut for creating an array, using the PHP array function:

 $data = array(123, "Hello", "Good day"); 

This creates the same array, starting from an index value of 0. If you wanted to start with an index value of 1, you could use the => operator like this:

 $data = array(1 => 123, "Hello", "Good day"); 

Now the array would look like this:

 $data[1] = 123; $data[2] = "Hello"; $data[3] = "Good day"; 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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