|
How to create PHP arrays
When you create a PHP array, remember that it's a special data type
that can store multiple values in the same variable. Think of an
array as set of variables that share the same name, rather than
one variable that has its value constantly replaced.
Each member of the array is known as an element, and each element
has a unique index within the array.
When you create a PHP array, the starting index value is zero by
default. However, you can set the index value for each element in
the array, as well as use string values. When a PHP array uses strings
for the index values, it is known as an associative array.
It's easy to create and initialize PHP arrays. There are two methods
to choose from, and we'll be discussing both of them in this article.
Create an array with the array() function
This is the method of choice when you have multiple values to assign
at one time. A common example is initializing an array of state
names to be used in a form. We'll be using a shorter example here.
$MyArray = array("Hello", "World");
Each element is surrounded by quotes and separated by commas. The
number of elements is variable, so you can specify as many elements
as you need to initialize the array.
Create an array with the array identifier
You can create a PHP array by using the array identifier, which
is a set of empty square brackets. We can create the same array
shown above using this method.
$MyArray[] = "Hello";
$MyArray[] = "World";
PHP will automatically assign the index value for each element
in the array. Although you can assign the index values if you want
to, it's easier to let PHP handle it. The array will work either
way, but if you skip numbers between the index values, PHP will
not initialize the intervening values. If this is what you intend,
fine. But if you make a mistake, this could cause trouble for your
script.
The PHP array identifier adds new elements
It's easy to add new elements to the end of a PHP with the array
identifier. For instance, if we wanted to add a new element to the
existing example array, we'd do this:
$MyArray[] = "!";
Note that you can mix these two methods. This will also work:
$MyArray = array("Hello", "World");
$MyArray[] = "!";
Defining the starting index value
By default, PHP arrays are zero-based. This means that the index
value for the last element is always one less than the total number
of elements. If you have an array of all 50 US states, the first
element would be $states[0], and the last one will be accessed as
$states[49]. If you'd like to change the default behavior, use the
=> operator.
$MyArray = array(1 => "Hello", "World",
"!");
Now the first element, "Hello", would be accessed as
$MyArray[1] instead of the default $MyArray[0].
More to come soon!
Work up through information obyained at About.com
|