Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Controlling Program Flow Mohammed M. Hassoun 2012.

Similar presentations


Presentation on theme: "PHP Controlling Program Flow Mohammed M. Hassoun 2012."— Presentation transcript:

1 PHP Controlling Program Flow Mohammed M. Hassoun 2012

2 Controlling Program Flow

3 The if Statement The simplest of PHP’s conditional statements is the if statement. This works much like the English-language statement, “if X happens, do Y.” Here’s a simple example, which contains a conditional statement that checks if the value of the $number variable is less than 0 and prints a notification message if so. <?php // if number is less than zero // print message $number = -88; if ($number < 0) { echo 'That number is negative'; } ?>

4 The if-else Statement The if statement is quite basic: it only lets you define what happens when the condition specified evaluates to true. But PHP also offers the if-else statement, an improved version of the if construct that allows you to define an alternative set of actions that the program should take when the condition specified evaluates to false. Using this statement often results in more compact and readable code, because it lets you combine two actions into a single, unified code block. In English, this statement would read, “if X happens, do Y; otherwise, do Z.” The if-elseif-else Statement The if-elseif-else statement lets you chain together multiple if-else statements, thus allowing the programmer to define actions for more than just two possible outcomes. Consider the following example, which illustrates its use:

5 <?php $today = 'Tuesday'; if ($today == 'Monday') { echo 'Monday\'s child is fair of face.'; } elseif ($today == 'Tuesday') { echo 'Tuesday\'s child is full of grace.'; } elseif ($today == 'Wednesday') { echo 'Wednesday\'s child is full of woe.'; } elseif ($today == 'Thursday') { echo 'Thursday\'s child has far to go.'; } elseif ($today == 'Friday') { echo 'Friday\'s child is loving and giving.'; } elseif ($today == 'Saturday') { echo 'Saturday\'s child works hard for a living.'; } else { echo 'No information available for that day'; } ?>

6 Here, the program will output a different message for each day of the week (as set in the $today variable). Notice also the final else branch: this is a “catch-all” branch, which will be triggered if none of the previous conditional statements evaluate to true, and it’s a handy way to account for situations that you can’t foresee. There’s one important thing to remember about the if-elseif-else construct: as soon as one of the conditional statements evaluates to true, PHP will execute the corresponding code, skip the remaining conditional tests, and jump straight to the lines following the entire if-elseif-else block. So, even if more than one of the conditional tests evaluates to true, PHP will only execute the code corresponding to the first true test. The switch-case Statement An alternative to the if-elseif-else statement is the switch-case statement, which does almost the same thing: it tests a variable against a series of values until it finds a match, and then executes the code corresponding to that match.

7 The while Loop The easiest type of loop to understand is the while loop, which repeats continuously while a prespecified condition is true. Here’s an example, which uses a loop to repeatedly print an 'x' to the output page. <?php // repeat continuously until counter becomes 10 // output: 'xxxxxxxxx' $counter = 1; while ($counter < 10) { echo 'x'; $counter++; } ?>

8 The do-while Loop With a while loop, the condition to be evaluated is tested at the beginning of each loop iteration. There’s also a variant of this loop, the do-while loop, which evaluates the condition at the end of each loop iteration. Here’s a revision of the preceding example that illustrates it in action: <?php // repeat continuously until counter becomes 10 // output: 'xxxxxxxxx' $counter = 1; do { echo 'x'; $counter++; } while ($counter < 10); ?>

9 The for Loop The while and do-while loops are fairly simple: they repeat for so long as the specified condition remains true. But PHP also supports a more sophisticated type of loop, the for loop, which is useful when you need to execute a set of statements a specific number of times. The best way to understand a for loop is by looking at some code. Here’s a simple example, which lists the numbers between 1 and 10: <?php // repeat continuously until counter becomes 10 // output: for ($x=1; $x<10; $x++) { echo "$x "; } for ($i=0, $k=10; $i<=10 ; $i++, $k--) { echo "Var ". $i. " is ". $k. " "; } ?>

10 Function What It Does empty() Tests if a string is empty strlen() Calculates the number of characters in a string strrev() Reverses a string str_repeat() Repeats a string substr() Retrieves a section of a string strcmp() Compares two strings str_word_count() Calculates the number of words in a string str_replace() Replaces parts of a string trim() Removes leading and trailing whitespace from a string strtolower() Lowercases a string strtoupper() Uppercases a string

11 ucfirst() Uppercases the first character of a string ucwords() Uppercases the first character of every word of a string addslashes() Escapes special characters in a string with backslashes stripslashes() Removes backslashes from a string htmlentities() Encodes HTML within a string htmlspecialchars() Encodes special HTML characters within a string nl2br() Replaces line breaks in a string with elements html_entity_decode() Decodes HTML entities within a string htmlspecialchars_decode() Decodes special HTML characters within a string strip_tags() Removes PHP and HTML code from a string

12 Working with Substrings PHP also allows you to slice a string into smaller parts with the substr() function, which accepts three arguments: the original string, the position (offset) at which to start slicing, and the number of characters to return from the starting position. The following listing illustrates this in action: <?php // extract substring // output: 'come' $str = 'Welcome to nowhere'; echo substr($str, 3, 4); ?> To extract a substring from the end of a string (rather than the beginning), pass substr() a negative offset, as in this revision of the preceding example: substr($str, -4, 4);

13 Comparing, Counting, and Replacing Strings If you need to compare two strings, the strcmp() function performs a case-sensitive comparison of two strings, returning a negative value if the first is “less” than the second, a positive value if it’s the other way around, and zero if both strings are “equal.” Here are some examples of how this works: <?php // compare strings $a = "hello"; $b = "hello"; $c = "hEllo"; // output: 0 echo strcmp($a, $b); // output: 1 echo strcmp($a, $c); ?>

14 PHP’s str_word_count() function provides an easy way to count the number of words in a string. The following listing illustrates its use: <?php // count words // output: 5 $str = "The name's Bond, James Bond"; echo str_word_count($str); ?> If you need to perform substitution within a string, PHP also has the str_replace() function, designed specifically to perform find-and-replace operations. This function accepts three arguments: the search term, the replacement term, and the string in which to perform the replacement. Here’s an example: <?php // replace '@' with 'at' // output: 'john at domain.net' $str = 'john@domain.net'; echo str_replace('@', ' at ', $str); ?>

15 Formatting Strings PHP’s trim() function can be used to remove leading or trailing whitespace from a string; this is quite useful when processing data entered into a Web form. Here’s an example: <?php // remove leading and trailing whitespace // output 'a b c' $str = ' a b c '; echo trim($str); ?> Changing the case of a string is as simple as calling the strtolower() or strtoupper() function. You can also uppercase the first character of a string with the ucfirst() function, or format a string in “word case” with the ucwords() function.

16 Working with HTML Strings PHP also has some functions exclusively for working with HTML strings. First up, the addslashes() function, which automatically escapes special characters in a string with backslashes. Here’s an example: <?php // escape special characters // output: 'You\'re awake, aren\'t you?' $str = "You're awake, aren't you?"; echo addslashes($str); ?>

17 You can reverse the work done by addslashes() with the aptly named stripslashes() function, which removes all the backslashes from a string. Consider the following example, which illustrates: <?php // remove slashes // output: 'John D'Souza says "Catch you later".' $str = "John D\'Souza says \"Catch you later\"."; echo stripslashes($str); ?>

18 The htmlentities() and htmlspecialchars() functions automatically convert special HTML symbols (like ) into their corresponding HTML representations (< and & gt;). Similarly, the nl2br() function automatically replaces newline characters in a string with the corresponding HTML line break tag. Here’s an example: <?php // replace with HTML entities // output: '<div width="200"> // This is a div</div>' $html = ' This is a div '; echo htmlentities($html); // replace line breaks with s // output: 'This is a bro // ken line' $lines = 'This is a bro ken line'; echo nl2br($lines); ?>

19 You can reverse the effect of the htmlentities() and htmlspecialchars() functions with the html_entity_decode() and htmlspecialchars_decode() functions. Finally, the strip_tags() function searches for all HTML and PHP code within a string and removes it to generate a “clean” string. Here’s an example: <?php // strip HTML tags from string // output: 'Please log in again' $html = ' Please log in again '; echo strip_tags($html); ?>

20 Thank You


Download ppt "PHP Controlling Program Flow Mohammed M. Hassoun 2012."

Similar presentations


Ads by Google