130 likes | 317 Views
PHP Arrays. Numerically Indexed Arrays Example 6-1. Adding items to an array < ? php $ paper [] = " Copier "; $ paper [] = " Inkjet "; $ paper [] = "Laser"; $ paper [] = " Photo "; print_r ($paper); ? >. Basic Access.
E N D
Numerically Indexed Arrays Example 6-1. Adding items to an array <?php $paper[] = "Copier"; $paper[] = "Inkjet"; $paper[] = "Laser"; $paper[] = "Photo"; print_r($paper); ?> Basic Access
Example 6-4. Adding items to an associative array and retrieving them <?php $paper['copier'] = "Copier & Multipurpose"; $paper['inkjet'] = "Inkjet Printer"; $paper['laser'] = "Laser Printer"; $paper['photo'] = "PhotographicPaper"; echo $paper['laser']; ?> AssociativeArrays
Example 6-5. Adding items to an array using the array keyword <?php $p1 = array("Copier", "Inkjet", "Laser", "Photo"); echo "p1 element: " . $p1[2] . "<br>"; $p2 = array('copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "PhotographicPaper"); echo"p2 element: " . $p2['inkjet'] . "<br>"; ?> Assignment Using the array Keyword
Example 6-6. Walking through a numeric array using foreach...as <?php $paper = array("Copier", "Inkjet", "Laser", "Photo"); $j = 0; foreach($paper as $item) { echo "$j: $item<br>"; ++$j; } ?> The foreach...as Loop
A simple design feature in PHP’s array syntax makes it possible to create arrays of more than one dimension • Example 6-10. Creating a multidimensional associative array MultidimensionalArrays
is_array() echo (is_array($fred)) ? "Is an array" : "Is not an array"; count() • To count all the elements in the top level of an array, use a command such as the following: echo count($fred); Using Array Functions
sort() sort($fred); shuffle() shuffle($cards); explode() <?php $temp = explode(' ', "This is a sentence with seven words"); print_r($temp); ?>
extract() • compact() • reset()