News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

How to Use the Array Command in PHP

Started by ganeshbala, Aug 20, 2008, 03:23 PM

Previous topic - Next topic

ganeshbala

How to Use the Array Command in PHP

Learn the syntax. The complete syntax is:

array ([index 1 =>] value 1, [index 2 =>] value 2, [index 2 =>] value 1[,]...).

The brackets "[]" indicate an optional part and the ellipsis "..." indicates you may continue the pattern as needed. Note that a trailing comma is an optional but valid syntax.


Understand how the indexes are generated. The first index will be 0 and each subsequent index will be incremented by one unless otherwise specified. The indexes and values may be strings or numeric. The last index overwrites the first index when two identical ones are specified.


Look at the following example for a simple array:

$myArray = array("red", "blue", "green");
?>

This example creates an array called myArray with the value "red" at index 0, the value "blue" at index 1 and the value "green" at index 2.


Look at this example of how to specify indexes:

$myArray = array(3=>"red", 2=>"blue", 1=>"green");
?>

This example creates an array called myArray with the value "red" at index 3, the value "blue" at index 2 and the value "green" at index 1.


Look at this example of how to initialize an array:

$myArray = array(3=>"red", "blue", "green");
?>

This example creates an array called myArray with the value "red" at index 3, the value "blue" at index 4 and the value "green" at index 5. Notice how the index is initialized to 3 and each subsequent index is incremented by one.