Difficulty: Moderately Easy
Things You’ll Need:
- PHP 5, installed and properly configured
- PHP IDE
- Web server (preferably Apache)
- MySQL database server, configured for work with PHP
Analyze the Data That Will Go Into the Array
Step1
Imagine that you have to write a movie catalog. One of the variables that you will use in your program is the movie title. But if you have thousands of movies, using a separate variable to store each title is not ideal. Instead, you should use one variable (the title) which has many values ("One Flew Over the Cuckoo's Nest," "The Graduate" and so on). Such data is an ideal candidate for an array.
Step2
Check to see if you already have a list of values, so that you can create the array with the array function instead of populating it manually.
Create the Array
Step1
Declare the array and assign values:
$titles = array("Hair", "The Office", "Troy", "Tarzan", "American Pie", "Adam and Eve", "Mystery", "E.T.", "Star Wars");
Enter as many movie titles as you have. If your values are strings, as in the above example, don't forget the quotes around them. If your values are integers, you can forgo the quotes.
Step2
Appreciate that this array is created with numeric indexing. In the above example, the array has nine elements (movie titles) and the indexes are from 0 ("Hair") to 8 ("Star Wars"). However, you can also create associative arrays.
Step3
Create an associative array. An associative array uses textual keys instead of numbers, and the indexes are more descriptive. This is especially useful when the values are not strings. The general syntax is the following:
$salary["John Smith"] = 3000;
This will assign the value 3000 to the array element, which has the "John Smith" index.
Step4
Use the array function to create the array.
$salary = array("John Smith" => 3000, "Sally Jones" => 4000, "Chris Steward" => 4900, "Mary Roberts" => 6500, "Sam Moses" => 5400, "Alice Roberts" => 4200);
Notice the slight difference in the syntax: You use the => symbol to enter the value for the key.
Perform Simple Operations With the Array
Step1
Reference values from the array by their index. For instance, if you want to display the title "Adam and Eve," you would do the following:
echo $titles[5];
because "Adam and Eve" is the sixth element in the array and its index is 5.
Step2
Assign values to array elements. If you want to set a new value for an array element, use the following:
$titles[6] = "Midnight Express";
This will replace the "Mystery" value with "Midnight Express".