How to Use the Array Command in PHP

By eHow Computers Editor

Rate: (4 Ratings)

The array command in PHP creates and returns an array with the listed parameters. Index values are optional and may be provided with the => operator. This command is a language construct, not a function. The following steps will aid in your search for information about this command.

Instructions

Difficulty: Moderately Challenging
Step1
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.
Step2
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.
Step3
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.
Step4
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.
Step5
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.

Post a Comment

POST A COMMENT

Request a New How-To Article

Looking for more How To information? Chances are there’s an eHow member who knows how to do what you’re looking to do. Submit an article request now!

eHow Article: How to Use the Array Command in PHP

eHow Computers Editor

eHow Computers Editor

Category: Computers

Articles: See my other articles

Related Ads