Specifications
Using PHP, we would write the following code to set up the data in the array shown in
Figure 3.3.
$products = array( array( “TIR”, “Tires”, 100 ),
array( “OIL”, “Oil”, 10 ),
array( “SPK”, “Spark Plugs”, 4 ) );
You can see from this definition that our products array now contains three arrays.
To access the data in a one-dimensional array, recall that we need the name of the array and the
index of the element. A two-dimensional array is similar, except that each element has two
indices—a row and a column. (The top row is row 0 and the far left column is column 0.)
To display the contents of this array, we could manually access each element in order like this:
echo “|”.$products[0][0].”|”.$products[0][1].”|”.$products[0][2].”|<BR>”;
echo “|”.$products[1][0].”|”.$products[1][1].”|”.$products[1][2].”|<BR>”;
echo “|”.$products[2][0].”|”.$products[2][1].”|”.$products[2][2].”|<BR>”;
Alternatively, we could place a for loop inside another for loop to achieve the same result.
for ( $row = 0; $row < 3; $row++ )
{
for ( $column = 0; $column < 3; $column++ )
{
echo “|”.$products[$row][$column];
}
echo “|<BR>”;
}
Both versions of this code produce the same output in the browser:
|TIR|Tires|100|
|OIL|Oil|10|
|SPK|Spark Plugs|4|
The only difference between the two examples is that your code will be shorter if you use the
second version with a large array.
You might prefer to create column names instead of numbers as shown in Figure 3.3. To do
this, you can use associative arrays. To store the same set of products, with the columns named
as they are in Figure 3.3, you would use the following code:
$products = array( array( Code => “TIR”,
Description => “Tires”,
price => 100
),
array( Code => “OIL”,
Description => “Oil”,
Using PHP
P
ART I
76
05 7842 CH03 3/6/01 3:42 PM Page 76