Creating Arrays - Examples
<< Arrays - Ordered Maps
<< PHP Tutorials - Herong's Tutorial Examples
This section provides a tutorial example on how to create arrays in different ways.
Here is a tutorial example PHP script to show you some of array rules described in the previous section:
<?php # ArrayTest.php # Copyright (c) 2003 by Dr. Herong Yang, http://www.herongyang.com/ # print "\nLibrary hours:\n"; $libraryHours = array( 'Monday - Friday'=>'09:00 - 21:00', 'Saturday'=>'09:00 - 17:00', 'Sunday'=>'closed'); print_r($libraryHours); # print "\nPrime numbers:\n"; $primeNumbers = array(3, 5, 7, 11); $primeNumbers[] = 13; print_r($primeNumbers); # print "\nFruits:\n"; $fruits[] = 'Apple'; $fruits[] = 'Orange'; $fruits[''] = 'Peach'; $fruits[''] = 'Banana'; $fruits['G'] = 'Grape'; $fruits['7'] = 'Pear'; $fruits[] = 'Fig'; print_r($fruits); # print "\nFruits array modified:\n"; unset($fruits[1]); $fruits[1] = 'Orange'; print_r($fruits); ?>
If you run this sample script, you should get:
Library hours: Array ( [Monday - Friday] => 09:00 - 21:00 [Saturday] => 09:00 - 17:00 [Sunday] => closed ) Prime numbers: Array ( [0] => 3 [1] => 5 [2] => 7 [3] => 11 [4] => 13 ) Fruits: Array ( [0] => Apple [1] => Orange [] => Banana [G] => Grape [7] => Pear [8] => Fig ) Fruits array modified: Array ( [0] => Apple [] => Banana [G] => Grape [7] => Pear [8] => Fig [1] => Orange )
The behavior of the $fruits array is very interesting. Review it carefully.
Last update: 2005.
Sections in This Chapter
What Is an Array?
Array Related Built-in Functions