1 / 26

PHP String Functions, User Functions and Pulling it All Together

PHP String Functions, User Functions and Pulling it All Together. Chapters 4 & 5. <?php // check for submit if (!isset($_POST['submit'])) {     // and display form ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

vallejoc
Download Presentation

PHP String Functions, User Functions and Pulling it All Together

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. PHP String Functions, User Functionsand Pulling it All Together Chapters 4 & 5

  2. <?php // check for submit if (!isset($_POST['submit'])) {     // and display form ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">     <input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi     <input type="checkbox" name="artist[]" value="N'Sync">N'Sync     <input type="checkbox" name="artist[]" value="Boyzone">Boyzone     <input type="checkbox" name="artist[]" value="Britney Spears">Britney Spears     <input type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull     <input type="checkbox" name="artist[]" value="Crosby, Stills & Nash">Crosby, Stills & Nash     <input type="submit" name="submit" value="Select">     </form> <?php     } else {     // or display the selected artists     // use a foreach loop to read and display array elements     if (is_array($_POST['artist'])) {         echo 'You selected: <br />';  foreach ($_POST['artist'] as $a) {            echo "<i>$a</i><br />";             }         }     else {         echo 'Nothing selected';     } } ?> Using an array to process multiple checkbox entries.

  3. Functions • Very straightforward in PHP • Functions are code modules within your PHP scripts that are useful for: • Repetitive tasks • Clarifying (by segmenting) your code • Points to cover: • Placement • Parameters • Return values • Scope

  4. Example 1 <?php // define a function functionmyStandardResponse() {     echo "Get lost, jerk!<br /><br />"; } // on the bus echo "Hey lady, can you spare a dime? <br />"; myStandardResponse(); // at the office echo "Can you handle Joe's workload, in addition to your own, while he's in Tahiti for a month? You'll probably need to come in early and work till midnight...<br />"; myStandardResponse(); // at the party echo "Hi, haven't I seen you somewhere before?<br />"; myStandardResponse(); ?>

  5. About Example 1 • Placed above any calls to it • Has no parameters • Does not return any value • Functions that return no value are most often used to display a message • That’s what this example does

  6. Function Format functionfunction_name (optional function arguments/parameters) {     statement 1...;     statement 2...;     .     statement n...; }

  7. Example 2 – one argument/parameter <?php // define a function function getCircumference($radius) {     echo "Circumference of a circle with radius $radius is ".sprintf("%4.2f", (2 * $radius * pi()))."<br />"; } // call the function with an argument getCircumference(10); // call the same function with another argument getCircumference(20); ?>

  8. Example 3 – two parameters <?php // define a function function changeCase($str, $flag) {     /* check the flag variable and branch the code */     switch($flag) {         case 'U':             print strtoupper($str)."<br />";             break;         case 'L':             print strtolower($str)."<br />";             break;         default:             print $str."<br />";             break;     } } // call the function changeCase("The cow jumped over the moon", "U"); changeCase("Hello Sam", "L"); ?> Parameter order matters!

  9. Example 4 – return value <?php // define a function function getCircumference($radius) {     // return value  return (2 * $radius * pi()); } /* call a function with an argument and store the result in a variable */ $result =getCircumference(10); /* call the same function with another argument and print the return value */ printgetCircumference(20); ?> Only one value can be returned this way!

  10. Example 5 – returning an array <?php /* define a function to accept a list of email addresses */ function getUniqueDomains($list) {     /* iterate over the list, split addresses, add domain part to another array */     $domains = array(); //declare array $domains     foreach ($list as $l) {         $arr = explode("@", $l);         $domains[ ] = trim($arr[1]);     }     // remove duplicates and return  return array_unique($domains); } // read email addresses from a file into an array $fileContents = file("data.txt"); /* pass the file contents to the function and retrieve the result array */ $returnArray = getUniqueDomains($fileContents); // process the return array foreach ($returnArray as $d) {     print "$d, "; } ?>

  11. Example 6 – multiple parameters <?php // define a function function introduce($name, $place) {     print "Hello, I am $name from $place"; } // call function introduce("Moonface", "The Faraway Tree"); ?>

  12. Example 7 – default values <?php // define a function function introduce($name="John Doe", $place="London") {     print "Hello, I am $name from $place"; } // call function introduce("Moonface"); ?>

  13. Example 7 – variable # arguments • <?php • // define a function • function someFunc() { •     // get the arguments •     $args = func_get_args(); •     // print the arguments •     print "You sent me the following arguments:"; • foreach ($args as $arg) { •         print " $arg "; •     } •     print "<br />"; • } • // call a function with different # arguments • someFunc("red", "green", "blue"); • someFunc(1, "soap"); • ?>

  14. Example 8 - Scope <?php // define a variable in the main program $today = "Tuesday"; // define a function function getDay() {     // define a variable inside the function  $today = "Saturday";     // print the variable     print "It is $today inside the function<br />"; } // call the function getDay(); // print the variable print "It is $today outside the function"; ?>

  15. Example 9 – global scope <?php // define a variable in the main program $today = "Tuesday"; // define a function function getDay() {     // make the variable global global $today;     // define a variable inside the function $today = "Saturday";     // print the variable     print "It is $today inside the function<br />"; } // print the variable print "It is $today before running the function<br />"; // call the function getDay(); // print the variable print "It is $today after running the function"; ?> Once a variable is declared global, it is available at the global level, and can be manipulated both inside and outside a function.

  16. Example 10 – arrays as arguments • <?php • // define a function • function someFunc() { •     // get the number of arguments passed •     $numArgs = func_num_args(); • // get the arguments •     $args = func_get_args(); •     // print the arguments •     print "You sent me the following arguments: "; •  for ($x = 0; $x < $numArgs; $x++) { •         print "<br />Argument $x: "; •         /* check if an array was passed and, if so, iterate and print contents */ •         if (is_array($args[$x])) { •             print " ARRAY "; •             foreach ($args[$x] as $index => $element) { •                 print " $index => $element "; •             } •         } •         else { •             print " $args[$x] "; •         } •     } • } • // call a function with different arguments • someFunc("red", "green", "blue", array(4,5), "yellow"); • ?>

  17. Example 11 – parameter passing <?php // create a variable $today = "Saturday"; // function to print the value of the variable function setDay($day) {     $day = "Tuesday";     print "It is $day inside the function<br />"; } // call function setDay($today); // print the value of the variable print "It is $today outside the function"; ?> Passing $today by value

  18. Example 12 – parameter passing <?php // create a variable $today = "Saturday"; // function to print the value of the variable function setDay(&$day) {     $day = "Tuesday";     print "It is $day inside the function<br />"; } // call function setDay($today); // print the value of the variable print "It is $today outside the function"; ?> Passing $today by reference

  19. String Processing • One of the most common uses of PHP is the processing of form data submitted by users. • Validation is extremely important • So is precision

  20. Miscellany • Concatenation – uses . or enclose all fields within double quotes. • Including escape sequences in strings • Use double quotes for “\\” - inserts backslash “\$” - inserts dollar sign “\r” – inserts carriage return “\”” – inserts double quote “\t” – inserts tab “\n” – inserts new line

  21. Popular String Functions 1 String length: • strlen(string_to_check) String searches: • strpos(string_to_search, string_to_search_for) • Returns first position of found string; if not found, returns FALSE • Use strict inequality check: !== (in place of !=) • Variation: stripos – it’s case insensitive • strstr(string_to_search, string_to_search_for) • Returns a substring from the beginning of the found string until the end of searched string • Variation: stristr • Also, strchr – search for substring starting with one specific character

  22. Popular String Functions 2 Extraction of substring (no search): • substr(str_to_search, start_pos, length) Replacing characters & substrings: • str_replace(str_to_replace, repl_str, string) • str_ireplace • substr_replace(string, repl_str, start_pos, length)

  23. Popular String Functions 3 Pulling strings apart: • strtok(string, separator) • Follow with strtok(separator) • Ex: $s = “ABC*DEF*GHI*JKL*MNO”; $s_token = strtok($s,”*”); while ($s_token != NULL) { echo “$s_token<br / >”; $s_token = strtok(“*”); }

  24. Popular String Functions 4 Converting between arrays and strings: • explode(separator, string) • Start with string, create array • implode(separator, array) • Start with array, create string

  25. Popular String Functions 5 Exact comparisons: • strcmp(str1, str2) - case sensitive • strcasecmp(str1, str2) - case insensitive Check for similar text: • similar_text(str1, str2) • Returns # characters in common • soundex and metaphone

  26. Popular String Functions 6 • nl2br(string) • Replaces all newlines with breaks

More Related