1 / 65

Control Structures, Arrays, User Defined Functions

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.

goro
Télécharger la présentation

Control Structures, Arrays, User Defined Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Control Structures, Arrays, User Defined Functions

  2. 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

  3. PHP – String operators • <?php$a = "Hello ";$b = $a."World!"; // $b = "Hello World!"$a = "Hello ";$a .= "World!";    // $a = "Hello World!"?>

  4. 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

  5. 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?

  6. 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?

  7. 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?

  8. 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

  9. 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 ..)

  10. 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;

  11. 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

  12. 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; }

  13. Foreach and Arrays • foreach loop • 2 forms: • foreach (array_expression as $value) • statement • foreach (array_expression as $key => $value) • statement

  14. 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

  15. PHP – Array functions • There are many array functions in PHP • Visit them at • http://us.php.net/manual/en/function.array-push.php

  16. User Defined functions

  17. 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

  18. 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

  19. 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);

  20. 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

  21. 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

  22. 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

  23. 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

  24. 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);

  25. 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); * * * * * * * * * * * *

  26. 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 * * * * * * * * * * * *

  27. 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 * * * * * * * * * * * *

  28. 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 * * * * * * * * * * * *

  29. 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 * * * * * * * * * * * *

  30. 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

  31. 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 * * * * * * * * * * * *

  32. 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.

  33. 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!

  34. 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!

  35. 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!

  36. 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.

  37. 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->

  38. 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

  39. 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)

  40. 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.

  41. 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!

  42. Variable scope

  43. 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

  44. 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

  45. Using Autoglobals cont.

  46. 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(); ?>

  47. 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

  48. $_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

  49. $_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

  50. $_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

More Related