650 likes | 758 Vues
Control Structures, Arrays, User Defined Functions. PHP – String operators. There are two string operators. The first is the concatenation operator (.), which returns the concatenation of its right and left arguments.
E N D
PHP – String operators • There are two string operators. • The first is the concatenation operator (.), which returns the concatenation of its right and left arguments. • The second is the concatenating assignment operator (.=), which appends the argument on the right side to the argument on the left side
PHP – String operators • <?php$a = "Hello ";$b = $a."World!"; // $b = "Hello World!"$a = "Hello ";$a .= "World!"; // $a = "Hello World!"?>
Array: A filing cabinet, or a LIST of variables $price[1] $price[2] 1 2 $price[3] 3 $price[4] 4 5 Value Index Variable Name
For Loop and Arrays For ($m=1; $m<=4; $m++) { print “now m is “.$m. “<br />”; } // that will print 1 2 3 4 For ($m=1; $m<=4; $m++) { $list[$m]= 3; } // that will put 3 in each location of $m Print $m[2]; // what will this print? For ($m=1; $m<=4; $m++) { $list[$m]= $m; } // that will put $m in each location of $m Print $m[2]; // what will this print? For ($m=1; $m<=4; $m++) { $list[$m]= 2*$m; } Print $m[2]; // what will this print?
For Loop and Arrays $FastFoods = array(“pizza”, “burgers”, “french fries”, “tacos”, “fried chicken”); for ($Count = 0; $Count < 5; ++$Count) { echo $FastFoods[$Count], “<br />”; } // what will this print?
While Loop and Arrays $m=1; While ($m<=7) { $list[$m]= 2*$m; $m=$m+2; } Print $list[5]; // what will this print? $m=1; While ($m<=7) { $list[$m]= 2*$m; $m=$m+2; } Print $list[4]; // what will this print?
PHP – Array functions $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // first index is 0 $arr["x"] = 42; // This adds a new element to // the array with key "x " unset($arr[5]); // removes element from the array unset($arr); // This deletes the whole array
PHP – Array functions $arr = array( 6, “cs356” “Perl”, 9); count returns # of elements in array $result = count( $arr ); 3 array_keys return the keys of an array as an array (indexed from 0 to ..) array_values return the values of an array as an array (indexed from 0 to ..)
PHP – Array functions • $arr = array( 6, “cs356” “Perl”, 9); • array_search -- Searches the array for a given value and returns the corresponding key if successful • $key = array_search(‘Perl', $arr); • // $key = cs356;
PHP – Array functions • $arr = array( 6, “cs356” “Perl”, 9); • array_pop Pop the element off the end of array • $language = array_pop($arr); 9 • array_push Push one or more elements onto the end of array • array_push($arr, “cgi", “php"); • // keys are 2 and 3 for cgi and php
Foreach and Arrays • foreach Statements • Used to iterate or loop through the elements in an array • Does not require a counter; instead, you specify an array expression within a set of parentheses following the foreachkeyword • The syntax for the foreach statement is: foreach ($array_name as $variable_name) { statements; }
Foreach and Arrays • foreach loop • 2 forms: • foreach (array_expression as $value) • statement • foreach (array_expression as $key => $value) • statement
PHP – foreach loop • $a = array(“cs356”=>”Perl”,”ct366”=>”PHP”, “Java”); • foreach ($a as $key => $value) echo “$key: $value<br>”; • cs356: Perl • ct366: PHP • 0: Java
PHP – Array functions • There are many array functions in PHP • Visit them at • http://us.php.net/manual/en/function.array-push.php
What is a function? Think of it as a machine. You put in some input(s), and it does some work, and produces some output(s) print "Four squared is".square(4); 4 square($n) 16 Four squared is 16
How do you make a functionYou define it like this: The syntax for defining a function is: <?php function name_of_function(parameters) { statements; } ?> function square($n) { $value=$n*$n; return $value; } • A parameter is a variable that is used within a function • Parameters are placed within the parentheses that follow the function name • Functions do not have to contain parameters • The set of curly braces (called function braces) contain the function statements} • Function statements do the actual work of the function and must be contained within the function braces
How do you make a functionYou define it like this: Function name function square($n) { $value=$n*$n; return $value; } // and then you "Call" it like this. $x=square(5); // or like this print square(6);
How do you make a functionYou define it like this: function square($n) { $value=$n*$n; return $value; } // and then you "Call" it like this. $x=square(5); // or like this print square(6); input ("argument, or "parameter") the parameter is a variable that is used within the function
How do you make a functionYou define it like this: function square($n) { $value=$n*$n; return $value; } // and then you "Call" it like this. $x=square(5); // or like this print square(6); output, or "return value" A return statement is a statement that returns a value to the statement that called the function . A function does not necessarily have to return a value
How do you make a functionYou define it like this: function square($n) { $value=$n*$n; return $value; } // and then you "Call" it like this. $x=square(5); // or like this print square(6); Using the function
How do you make a functionYou define it like this: function square($n) { $value=$n*$n; return $value; } // and then you "Call" it like this. $x=square(5); // or like this print square(6); $x is now 25 36
A parameter can be an array Consider this example: $invoice[0]=24.95; $invoice[1]=188.40; $invoice[2]=33.22; ... Here's a function to compute the total of the invoices. function total($n,$list){ $sum=0; for ($i=0; $i<$n; $i++){ $sum=$sum+$list[$i]; } return $sum; } total(5,$invoice);
More Complicated Function function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); * * * * * * * * * * * *
More Complicated Function function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); Function name * * * * * * * * * * * *
More Complicated Function function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); arguments, or parameters * * * * * * * * * * * *
More Complicated Function function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); output value * * * * * * * * * * * *
More Complicated Function function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); Function Declaration * * * * * * * * * * * *
More Complicated Function function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); * * * * * * * * * * * * Function Invocation
Returning a value function makebox($height,$width) { $answer='<table>'; for ($row=1; $row<=$height;$row++) { $answer .='<tr>'; for ($col=1; $col<=$width; $col++) { $answer.='<td>*</td>'; } $answer .='</tr>'; } $answer .='</table>'; return $answer; } print makebox(3,4); Return statement * * * * * * * * * * * *
NOT Returning a value Not all functions have to return a value. Sometimes they just print their results... like this function printbold($text) { print "<strong>$text</strong>"; } print "I am "; printbold("Laura Croft"); print " and you are not."; I am Laura Croft and you are not.
Function Exercise 1 Create a function called print3times($text), that produces three copies of the given text, each on a separate row. (Use the <br /> tag.) function print3times($text) { ? ? you design what goes in here. ? } print3times('Hooray no Ike!'); Hooray no Ike! Hooray no Ike! Hooray no Ike!
Function Exercise 1 Create a function called print3times($text), that produces three copies of the given text, each on a separate row. (Use the <br /> tag.) function print3times($text) { // the BFI ("brute force & ignorance") method: print $text.'<br />'; print $text.'<br />'; print $text.'<br />'; } print3times('Hooray no Ike!'); Hooray no Ike! Hooray no Ike! Hooray no Ike!
Function Exercise 1 Create a function called print3times($text), that produces three copies of the given text, each on a separate row. (Use the <br /> tag.) function print3times($text) { // the elegant (extensible) method for ($i=1; $i<=3; $i++) { print $text.'<br />'; } } # print3times print3times('Hooray no Ike!'); Hooray no Ike! Hooray no Ike! Hooray no Ike!
Function Exercise 2 SIMPLE Create a function called polite($g,$name) where input $g will be 'm' or 'f' for male or female. It prints "Good morning Mr. Smith." or "Good morning, Ms. Smith." based on input like this: polite('m','Smith'). ADVANCED: In the fictional language Ispanglish, all female names end in 'a' and all male names end in 'e'. Produce a function called ispolite($name) that prints "BoonieDoozie, Madama Elena" for a female name like Elena, "BoonieDoozie, Maestro Mike' for a mail name like Mike.
Function Exercise 2 SIMPLE Create a function called polite($g,$name) where input $g will be 'm' or 'f' for male or female. It prints "Good morning Mr. Smith." or "Good morning, Ms. Smith." based on input like this: polite('m','Smith'). That is, the parameter $g will have value 'm' or 'f'. function polite ($g, $name){ if (something) { print "Good morning Mr. $name";} else { print "Good morning Ms. $name." } } polite('m','Jones'); polite('f','Ramirez'); Hint-> Calls->
Function Exercise 2 SIMPLE Create a function called polite($g,$name) where input $g will be 'm' or 'f' for male or female. It prints "Good morning Mr. Smith, or Ms. Smith.", based on input like polite('m','Smith'). function polite($g,$name) { if ($g=='m') { print "Good morning Mr. $name";} else { print "Good morning Ms. $name";} } Basic Solution
Function Exercise 2 SIMPLE Create a function called polite($g,$name) where input $g will be 'm' or 'f' for male or female. It prints "Good morning Mr. Smith, or Ms. Smith.", based on input like polite('m','Smith'). function polite($g,$name) { if ($g=='m') { print "Good morning Mr. $name";} else if ($g == 'f') { print "Good morning Ms. $name";} else { print "error 001: unknown gender selector $g.";} } Better Solution - covers all cases - numbered error msgs - specific feedback on type of error (could be better)
Function Exercise 2 ADVANCED: In the fictional language Ispanglish, all female names end in 'a' and all male names end in 'e'. Produce a function called ispolite($name) that prints "BoonieDoozie, Madama Elena" for a female name like Elena, "BoonieDoozie, Maestro Mike' for a male name like Mike.
Function Exercises An Answer to Function Exercise 2 ADVANCED: In the fictional language Ispanglish, all female names end in 'a' and all male names end in 'e'. Produce a function called ispolite($name) that prints "BoonieDoozie, Madama Elena" for a female name like Elena, "BoonieDoozie, Maestro Mike' for a male name like Mike. function ispolite($name){ $len=strlen($name); $last=substr($name,$len-1,1); if ($last = = 'a‘){ print "BoonieDoozie, Madama $name"; }else{ print "BoonieDoozie, Maestro $name"; } } // It SHOULD include an error case ... no space here!
Understanding Variable Scope • Variable scope is where in your program a declared variable can be used • A variable’s scope can be either global or local • A global variable is one that is declared outside a function and is available to all parts of your program • A local variable is declared inside a function and is only available within the function in which it is declared
Using Autoglobals • PHP includes various predefined global arrays, called autoglobals or superglobals • Autoglobals contain client, server, and environment information that you can use in your scripts • Autoglobals are associative arrays – arrays whose elements are referred to with an alphanumeric key instead of an index number
Understanding Variable Scope • Sample Code: Using keyword global <?php $GlobalVariable= “Global variable”; function scopeExample() { global $GlobalVariable; echo “<p>$GlobalVariable</p>”; } scopeExample(); ?> • Using the $GLOBALS autoglobal <?php $GlobalVariable= “Global variable”; function scopeExample() { echo “<p>”, $GLOBALS [“GlobalVariable”], “</p>”; } scopeExample(); ?>
Using Autoglobals (continued) • Use the global keyword to declare a global variable within the scope of a function • Use the $GLOBALSautoglobal to refer to the global version of a variable from inside a function • $_GET is the default method for submitting a form • $_GET and $_POST allow you to access the values of forms that are submitted to a PHP script
$_Get and $_Post Autoglobal • $_GET appends form data as one long string to the URL specified by the action attribute • $_GET • Appends form data as a string to the URL specified by the action attribute • Form data is submitted as name=value pairs • The name portion becomes the key of an element in the $_GET autoglobal and the value portion becomes the value of the element • Remember autoglobals are associative arrays • $_POST sends form data as a transmission separate from the URL specified by the action attribute • $_POST • Operates in a similar fashion to $_GET using name=value pairs • Doesn’t display form data in the address bar – more secure • Not limited to 1024 characters using $_GET • Some variance on this limit • W3C has guidelines on usage • http://www.w3.org/2001/tag/doc/whenToUseGet.html
$_Get and $_Post Autoglobal <form method=“get” or method=“post” action=“ProcessOrder.php”> <p>Name<br /> <input type=“text” name=“name” size=“50” /><br /> Address<br /> <input type=“text” name=“address” size=“50” /> <br /> City, State, Zip<br /> <input type=“text” name=“city” size=“38” /> <input type=“text” name=“state” size=“2” maxlength=“2” /> <input type=“text” name=“zip” size=“5” maxlength=“5” /> <br /> E-Mail<br /> <input type=“text” name=“email” size=“50” /></p> <p> input type=“reset” /> <input type=“submit” /></p> </form> Value=info typed in the form Name= this literal
$_Get and $_Post Autoglobal • $_GET • $_GET[“name”] • $_GET[“address”] • $_GET[“city”] • $_GET[“state”] • $_GET[“zip”] • $_GET[“email”] • Using the name of the form element as a key in the associative array to access it’s value