This site is an assignment site for study group of
Hello World forum.
Together we are studying the book
Larry Ullman PHP For World Wide Web.
Chapter 7: Using Arrays
- What Is an Array?
Creating an Array
Adding Items to an Array
Accessing Array Elements
Creating Multidimensional Arrays
Sorting Arrays
Transforming Between Strings and Arrays
Creating an Array from a Form
What Is an Array?
Arrays are essential for storing, managing, and operating on sets of variables. It can hold more information than a simple string.
Syntactical rules for arrays:
- Begin with a dollar sign.
- Continue with a letter or underscore.
- Finnish with any combination of letters, numbers or the underscore
Greating an Array
$days = array (1 => 'Monday' , 2 => 'Tuesday' , 3 => 'Wednesday');
Adding Items to an Array
An array looks the same than a variable, except it can include a key, the key needs to set into a square brackets([]). It's optional to specify the key or not.
- $days[] ='Monday';
$days[] ='Tuesday'; -
Any existing value already indexed do get overwritten in that location when you specify the key.
- $days[1] ='Monday';
- $days[2] ='Tuesday';
Merging Arrays: the function array_merge()
- $new_array = array_merge ($array1,$array2);
Deleting Arrays and Array Elements: the function unset()
- unset ($array[4]]; or unset ($array['name']); or reseting an array $array = array()
Accessing Array Elements:the function foreach
Foreach function loop iterates through every element of the the unkeyed array, assigning each index and each value.
- foreach ($array as $value){
- //Do whatever.
- }
Sorting Arrays
| Function | Sorts by | Maintains Key Values |
|---|---|---|
| sort() | values | no |
| rsort() | values inverse | no |
| asort() | values | yes |
| arsort() | values inverse | yes |
| ksort() | keys | yes |
| krsort() | keys inverse | yes |
extract() function can be used to access array values.
list() function for retrievingvalues from a database.
implode() function turns an array into a string.
explode() function turns a string into an array.
Creating an array from a form
Name the Event into this next textfield and choose a day or days.