~~SLIDESHOW~~ ====== Introduction to PHP (Part 2) ====== **Supplementary Material** Provided for Reference. This material is no longer taught on this module. **Lecturer**: [[C.P.Jobling@Swansea.ac.uk|Dr Chris P. Jobling]]. More on the language features of PHP ===== Introduction to PHP (Part 2) ===== We continue our review of the Basics of PHP with a discussion of //arrays//, //functions// and //regular expressions//. ---- Based on Chapter 12 of Robert W. Sebasta, //Programming the World-Wide Web//, 3rd Edition, Addison Wesley, 2006. and Chapter 12 of Chris Bates, //Web Programming: Building Internet Applications//, 3rd Edition, John Wiley, 2006. ===== Contents of this Lecture ===== //Further features of the PHP language with examples// * [[eg-259:lecture17#arrays|Arrays]] * [[eg-259:lecture17#functions|Functions]] * [[eg-259:lecture17#pattern_matching|Pattern Matching]] The [[eg-259:examples:php1#examples_from_lecture_17|Examples for PHP Part 2]]. ===== Learning Outcomes ==== //At the end of this lecture you should be able to answer these questions//: - In what two ways can arrays in PHP be created? - What keys are used when an array is created but no keys are specified? - Must all of the values of an array be of the same type? - Must all of the keys of an array be of the same type? - What exactly do the ''array_keys'' and ''array_values'' functions do? ===== Learning Outcomes (continued) ===== //At the end of this lecture you should be able to answer these questions//: - What exactly does the ''in_array'' function do? - Explain the actions of the ''implode'' and ''explode'' functions. - Describe the actions of the ''next'', ''reset'', and ''prev'' functions. - What are the syntax and semantics of the two forms of the ''foreach'' statement? - Describe the result of using the ''sort'' function on an array that has both string and numeric values. ===== Learning Outcomes (continued) ===== //At the end of this lecture you should be able to answer these questions//: - What is the difference between the ''sort'' and ''asort'' functions? - What happens if a script defines the same function more than once? - Are function names case sensitive? - What value is returned by a function if its execution does not end by executing a ''return'' statement? ===== Learning Outcomes (continued) ===== //At the end of this lecture you should be able to answer these questions//: - What are the two ways you can specify that a parameter is to be passed by reference? - How can a variable used outside a function be accessed by the function? - How can you define a variable in a function so that its lifetime extends beyond the time the function is in its first execution? ===== Arrays ===== * Not like the arrays of any other programming language * A PHP array is a //generalization// of the arrays of other languages * A PHP array is really a mapping of keys to values, where the keys can be numbers (to get a //traditional// array) or strings (to get a //associative// array) ===== Array creation ===== * Use the ''array()'' construct, which takes one or more ''key => value'' pairs as parameters and returns an array of them * The keys are non-negative integer literals or string literals * The values can be anything * //Example//: $list = array(0 => "apples", 1 => "oranges", 2 => "grapes") * This is a "regular" array of strings ===== Array creation (continued) ===== * If a key is omitted and there have been integer keys, the default key will be the largest current key + 1 * If a key is omitted and there have been no integer keys, 0 is the default key * If a key appears that has already appeared, the new value will overwrite the old one ===== Array elements ===== * Arrays can have mixed kinds of elements * //Some examples//: $list = array("make" => "Cessna", "model" => "C210", "year" => 1960, 3 => "sold"); $list = array(1, 3, 5, 7, 9); $list = array(5, 3 => 7, 5 => 10, "month" => "May"); $colours = array('red', 'blue', 'green', 'yellow'); ===== Accessing array elements ===== * //Use brackets//: $list[4] = 7; $list["day"] = "Tuesday"; $list[] = 17; * If an element with the specified key does not exist, it is created * If the array does not exist, the array is created ===== Accessing array elements ===== * The keys or values can be extracted from an array: $highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67, "Thu" => 62, "Fri" => 65); $days = array_keys($highs); $temps = array_values($highs); ===== Dealing with Arrays ===== * An array can be deleted with ''unset'': unset($list); unset($list[4]); # No index 4 element now * ''is_array($list)'' returns ''true'' if ''$list'' is an array * ''in_array(17, $list)'' returns true if 17 is an element of ''$list'' ===== Dealing with Arrays (continued) ===== * ''explode(" ", $str)'' creates an array with the values of the words from ''$str'', split on a space * ''implode(" ", $list)'' creates a string of the elements from ''$list'', separated by a space ===== Internal structure of arrays ===== {{eg-259:l17-logical-structure.png|The logical internal structure of arrays in PHP}} ===== Sequential access to array elements ===== * Use ''current'' and ''next'': $colours = array("blue", "red", "green", "yellow"); $colour = current($colours); print("$colour
"); while ( $colour = next($colours) ) { print ("$colour
"); }
* This does not always work -- for example, if the value in the array happens to be ''FALSE'' ===== Sequential access to array elements (continued) ===== * //Alternative//: use ''each'', instead of ''next'': while ( $element = each($colours) ) { print ("$element['value']
"); }
* The ''prev'' function moves ''current'' backwards ===== Sequential access to array elements (continued) ===== * To implement stacks with an array use ''array_push($list, $element)'' and ''array_pop($list)'' ===== Sequential access to array elements (continued) ===== * To visit every element of an array use ''foreach (array_name as scalar_name) { ... }:'' foreach ($colours as $colour) { print "Is $colour your favourite colour?
"; }
* //produces//: Is red your favourite colour? Is blue your favourite colour? Is green your favourite colour? Is yellow your favourite colour? ===== Sequential access to array elements (continued) ===== * ''foreach'' can iterate through both //keys// and //values//: foreach ($colours as $key => $colour) { ... } * Inside the compound statement, both ''$key'' and ''$colour'' are defined * //Example//: $ages = array("Bob" => 42, "Mary" => 43); foreach ($ages as $name => $age) { print("$name is $age years old
"); }
===== Sorting Arrays ===== * ''sort'' sorts the values of an array, leaving the keys in their present order -- intended for traditional arrays *e.g., ''sort($list);'' * The ''sort'' function does not return anything * Works for both strings and numbers, even mixed strings and numbers: $list = ('h', 100, 'c', 20, 'a'); sort($list); // Produces ('a', 'c', 'h'‘, 20, 100) ===== Sorting Arrays (continued) ===== * In PHP 4+, the sort function can take a second parameter, which specifies a particular kind of sort: sort($list, SORT_NUMERIC); ===== More sorting functions ===== * ''asort'' sorts the values of an array, while keeping the key/value relationships -- intended for associative arrays * ''rsort'' sorts the values of an array into reverse order * ''ksort'' sorts the elements of an array by the keys, maintaining the key/value relationships e.g.: $list("Fred" => 17, "Mary" => 21, "Bob" => 49, "Jill" => 28); ksort($list); // $list is now ("Bob" => 49, "Fred" => 17, "Jill" => 28, "Mary" => 21) * ''krsort'' sorts the elements of an array by the keys into reverse order ===== Example of Array Sorting ===== * An example to illustrate several of the sorting functions: [[/eg-259/examples/lecture17/sorting.php|sorting.php]] ([[http://localhost/eg-259/examples/lecture17/sorting.php|sorting.php @ localhost]]) ---- * //Code//: < sorting.php - An example to illustrate several of the sorting functions 31, "Al" => 27, "Gandalf" => "wizzard", "Betty" => 42, "Frodo" => "hobbit"); ?>

Original Array

$value) { print("[$key] => $value
"); } ?>

Array sorted with sort

$value) { print("[$key] = $value
"); } ?>

Array sorted with asort

$value) { print("[$key] = $value
"); } ?>

Array sorted with ksort

$value) { print("[$key] = $value
"); } ?>
* //Result//: {{eg-259:l17-sorting.png|Result of running the sort.php example}} ===== User-Defined Functions ===== * //Syntactic form//: function function_name( [formal_parameters] ) { ... } ===== General Characteristics of Functions ===== * Functions need not be defined before they are called (in PHP 3, they must) * Function overloading is not supported((PPHP 5 supports classes, so it may be possible to use overloading for polymorphism)) * If you try to redefine a function, it is an error * Functions can have a variable number of parameters * Default parameter values are supported * Function definitions can be nested * Function names are not case sensitive * The ''return'' function is used to return a value; if there is no ''return'', there is no returned value ===== Function Parameters ===== * If the caller sends too many actual parameters, the subprogram ignores the extra ones * If the caller does not send enough parameters, the unmatched formal parameters are ''unbound'' * The default parameter passing method is //pass by value// (one-way communication) ===== Function Parameters (continued) ===== * To specify //pass-by-reference//, prepend an ampersand to the formal parameter: function addOne(&$param) { $param++; } $it = 16; addOne($it); // $it is now 17 ===== Function Parameters (continued) ===== * If the function does not specify its parameter to be pass by reference, you can prepend an ampersand to the actual parameter and still get pass-by-reference semantics: function subOne($param) { $param--; } $it = 16; subOne(&$it); // $it is now 15 ===== Return Values ===== * Any type may be returned, including objects and arrays, using the ''return'' * If a function returns a reference, the name of the function must have a prepended ampersand: function &newArray($x) { ... } ===== The Scope of Variables ===== * An undeclared variable in a function has the scope of the function * To access a nonlocal variable, it must be declared to be //global//, as in: global $sum; ===== The Lifetime of Variables ===== * Normally, the lifetime of a variable in a function is from its first appearance to the end of the function's execution: static $sum = 0; # $sum is static ===== Pattern Matching ===== * PHP has two kinds: * POSIX * Perl-compatible (''preg'') preg_match(regex, str [,array]) * The optional ''array'' is where to put the matches ===== Example ===== The [[/eg-259/examples/lecture17/word_table.php|word_table.php]] ([[http://localhost/eg-259/examples/lecture17/word_table.php|word_table.php @ localhost]]) example illustrates the use of functions and regular expressions ---- * //Code//: Word Table Word Frequency

"; $sorted_keys = array_keys($tbl); sort($sorted_keys); foreach ($sorted_keys as $word) { print "$word $tbl[$word]
"; } ?>
* Output of the example script Word Frequency apples 3 are 1 better 1 don't 1 for 1 good 1 like 2 maybe 1 or 2 oranges 1 than 1 you 3 ===== Summary of this Lecture ===== //Further features of the PHP language with examples// * [[eg-259:lecture17#arrays|Arrays]] * [[eg-259:lecture17#functions|Functions]] * [[eg-259:lecture17#pattern_matching|Pattern Matching]] The [[eg-259:examples:php1#examples_from_lecture_17|Examples for PHP Part 2]]. ===== Learning Outcomes ==== //At the end of this lecture you should be able to answer these questions//: - In what two ways can arrays in PHP be created? - What keys are used when an array is created but no keys are specified? - Must all of the values of an array be of the same type? - Must all of the keys of an array be of the same type? - What exactly do the ''array_keys'' and ''array_values'' functions do? ===== Learning Outcomes (continued) ===== //At the end of this lecture you should be able to answer these questions//: - What exactly does the ''in_array'' function do? - Explain the actions of the ''implode'' and ''explode'' functions. - Describe the actions of the ''next'', ''reset'', and ''prev'' functions. - What are the syntax and semantics of the two forms of the ''foreach'' statement? - Describe the result of using the ''sort'' function on an array that has both string and numeric values. ===== Learning Outcomes (continued) ===== //At the end of this lecture you should be able to answer these questions//: - What is the difference between the ''sort'' and ''asort'' functions? - What happens if a script defines the same function more than once? - Are function names case sensitive? - What value is returned by a function if its execution does not end by executing a ''return'' statement? ===== Learning Outcomes (continued) ===== //At the end of this lecture you should be able to answer these questions//: - What are the two ways you can specify that a parameter is to be passed by reference? - How can a variable used outside a function be accessed by the function? - How can you define a variable in a function so that its lifetime extends beyond the time the function is in its first execution? ===== Homework Exercises ===== Write the following PHP functions and code to test them - //Parameter//: An array of strings. //Return value//: A list of the unique strings in the parameter array. - //Parameter//: an array of numbers. //Return value//: The average and median of the parameter array. - //Parameter//: A string of numbers separated by spaces. //Return value//: The first four-digit number in the string. ===== Homework Exercises (continued) ===== - Modify the sample script ''word_table.php'' discussed in this lecture to place the output table in an XHTML table. These and other PHP exercises are also available on the [[eg-259:homework:17|homework page]]. ===== What's Next? ===== **PHP for Web Applications** * [[eg-259:lecture18#queries_and_query_strings|Queries and Query Strings]] * [[eg-259:lecture18#form_handling|Form Handling]] * [[eg-259:lecture18#files|Files]] * [[eg-259:lecture18#storing_information_about_client_state|Storing Information about Client State]] * [[eg-259:lecture18#session_tracking|Session Tracking]] [[eg-259:lecture16|Previous Lecture]] | [[eg-259:home]] | [[eg-259:lecture18|Next Lecture]]