Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

Listing 5.4 Initializing an Array


<?
$monthName = array(1=>"January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December");


print("Month 5 is $monthName[5]
\n");
?>


Listing 5.5 Using an Array to Translate Values


<?
$monthName = array(
1=>"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December",
"Jan"=>"January", "Feb"=>"February",
"Mar"=>"March", "Apr"=>"April",
"May"=>"May", "Jun"=>"June",
"Jul"=>"July", "Aug"=>"August",
"Sep"=>"September", "Oct"=>"October",
"Nov"=>"November", "Dec"=>"December",
"January"=>"January", "February"=>"February",
"March"=>"March", "April"=>"April",
"May"=>"May", "June"=>"June",
"July"=>"July", "August"=>"August",
"September"=>"September", "October"=>"October",
"November"=>"November", "December"=>"December"
);


print("Month 5 is ". $monthName[5]. "
\n");
print("Month Aug is ". $monthName["Aug"]. "
\n");
print("Month June is ".
$monthName["June"]. "
\n");
?>


Multidimensional Arrays


An array element can be any type of data. You've seen numbers and strings, but you can
even put an array inside an array. An array of arrays is also called a multidimensional
array. Imagine a ten-by-ten grid. You've got 100 different squares, each of which can
have its own value. One way to represent this in code is a two-dimensional array: a ten-
element array of ten-number arrays, ten rows of ten columns.


To reference a single element, you first use square brackets to pick the first dimension
(row), then use a second pair of brackets to pick the second dimension (column). Row 3,
column 7, would be written as $someArray[3][7].


Listing 5.6 initializes a multidimensional array using the array function. This shows that
multidimensional arrays are just arrays of arrays.

Free download pdf