-
Using the
array()
function$a = array('I', 'II', 'III', 'IV');
-
Successively adding values to an array using the variable name and square brackets
$a[] = 'I'; $a[] = 'II'; $a[] = 'III'; $a[] = 'IV';
Associative Array
When using associative arrays, the same two methods can be used; however, this time keys and values must be provided:
$a1 = array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'); $a2['one'] = 'I'; $a2['two'] = 'II'; $a2['three'] = 'III'; $a2['four'] = 'IV';
Arrays can also be nested, when an array element itself is an array:
$a = array( 'Roman' => array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'), 'Arabic' => array('one' => '1', 'two' => '2', 'three' => '3', 'four' => '4') );
Now, the Arabic representation of the number four can be accessed using $a['Arabic']['four']
.
Of course, arrays are not only created within a script, but can also come from other sources, including from HTML forms (see tutorial 4, "Interacting with Web Forms") and from cookies and sessions (see tutorial 5, "Remembering Users (Cookies and Sessions)"). But if the array is there, what's next? The following give some pointers.