Download presentation
Presentation is loading. Please wait.
Published byAubrey Dorsey Modified over 8 years ago
1
Arrays
2
Indexed Arrays Use numbers as keys: $grades = array(); $grades[0] = ' A ' ; $grades[1] = ' A- ' ; $grades[2] = ' B+ ' ; Or with one statement: $grades = array( ' A ', ' A- ', ' B+ ') ; Each item in the array is a key/value pair.
3
Associative Arrays Use strings as keys: $states = array(); $states[ ' NC ' ] = ' North Carolina ' ; $states[ ' CO ' ] = ' Colorado ' ; $states[ ' IA ' ] = ' Iowa ' ; Or: $states = array( ' NC ' => ' North Carolina ', ' CO ' => ' Colorado ', ' IA ' => ' Iowa ') ;
4
Output with Arrays Numeric keys don't need quotes: echo $grades[0]; Character-based keys do need quotes: echo $states['CO']; But output as part of a string is problematic. Options are: Concatenation: echo 'I grew up in '. $states['CO']; Curly brackets: echo "I grew up in {$states['CO']}"; Use a simpler variable: $myState=$states['CO']; Nesting quotes with associative arrays gives a parse error: echo "I grew up in $states['CO']"; //doesn't work!!
5
Alternative Array Creation $months = $array (1 => 'January', 'February', 'March', …); This sets the first numeric key value to 1. The remaining keys will be automatically generated incrementing by 1. The range() function can be used to create an array of sequential numbers: $die = range (1, 6); $lc_letters = range ('a', 'z');
6
Array Processing To access every array element use a foreach loop: $vowels = array('a', 'e', 'i', 'o', 'u'); foreach ($array as $value) { echo $value.' '; } //Don't forget to close the curly brace to end the loop //Output:
7
Array Processing Associative array example: $countryCodes = array('DEU' => 'Germany', 'JPN' => 'Japan', 'ARG' => 'Argentina'); foreach ($countryCodes as $key => $value) { echo "The code for $value is $key. "; } //Output:
8
Array Testing and Debugging The print_r() function will show you the contents of an array, both keys and values. print_r() is not intended for Web output. It is a testing and debugging tool. As such, it should be removed before the final version is published.
9
PHP's Built-in Superglobal Arrays Begin with $_ followed by an all caps name: Examples: $_GET $_POST $_SERVER $_FILES ◦These arrays are automatically populated by the PHP interpreter and are used frequently. ◦The syntax is exactly the same as for user-defined arrays.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.