php string functions, user functions and pulling it all together chapters 4 & 5
Post on 21-Dec-2015
223 views
TRANSCRIPT
PHP String Functions, User Functions
and Pulling it All Together
Chapters 4 & 5
<?php// check for submitif (!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.
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
Example 1<?php// define a functionfunction myStandardResponse() { echo "Get lost, jerk!<br /><br />";}
// on the busecho "Hey lady, can you spare a dime? <br />";myStandardResponse();
// at the officeecho "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 partyecho "Hi, haven't I seen you somewhere before?<br />";myStandardResponse();?>
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
Function Format
function function_name (optional function arguments/parameters) {
statement 1...;
statement 2...;
.
statement n...;
}
Example 2 – one argument/parameter
<?php// define a functionfunction getCircumference($radius) { echo "Circumference of a circle with radius $radius
is ".sprintf("%4.2f", (2 * $radius * pi()))."<br />";}// call the function with an argumentgetCircumference(10);// call the same function with another argumentgetCircumference(20);?>
Example 3 – two parameters<?php// define a functionfunction 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!
Example 4 – return value
<?php// define a functionfunction 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 */print getCircumference(20);?>
Only one value can be returned this way!
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 arrayforeach ($returnArray as $d) { print "$d, ";}?>
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");
?>
Example 7 – default values
<?php// define a functionfunction introduce($name="John Doe",
$place="London") { print "Hello, I am $name from $place";}// call functionintroduce("Moonface");?>
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");• ?>
Example 8 - Scope
<?php// define a variable in the main program$today = "Tuesday";// define a functionfunction getDay() { // define a variable inside the function $today = "Saturday"; // print the variable print "It is $today inside the function<br />";}// call the functiongetDay();// print the variableprint "It is $today outside the function";?>
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 variableprint "It is $today before running the function<br />";// call the functiongetDay();// print the variableprint "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.
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");• ?>
Example 11 – parameter passing
<?php// create a variable$today = "Saturday";// function to print the value of the variablefunction setDay($day) { $day = "Tuesday"; print "It is $day inside the function<br />";}// call functionsetDay($today);// print the value of the variableprint "It is $today outside the function";?>
Passing $today by value
Example 12 – parameter passing
<?php// create a variable$today = "Saturday";// function to print the value of the variablefunction setDay(&$day) { $day = "Tuesday"; print "It is $day inside the function<br />";}// call functionsetDay($today);// print the value of the variableprint "It is $today outside the function";?>
Passing $today by reference
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
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
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
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)
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(“*”);
}
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
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
Popular String Functions 6
• nl2br(string)– Replaces all newlines with breaks