PHP Controlling Program Flow Mohammed M. Hassoun 2012.

Slides:



Advertisements
Similar presentations
LIS651 lecture 1 PHP basics, database introduction Thomas Krichel
Advertisements

Creating PHP Pages Chapter 7 PHP Decisions Making.
Objectives Using functions to organize PHP code
PHP Conditions MIS 3501, Fall 2014 Jeremy Shafer Department of MIS Fox School of Business Temple University September 11, 2014.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
ITC 240: Web Application Programming SUBHASH PRAJAPATI 04/14/15.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Operations & Strings CSCI 116 Web Programming I. 2 Arithmetic Operators Arithmetic operators are used to perform mathematical calculations.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
UNIT II Decision Making And Branching Decision Making And Looping
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
PHP Workshop ‹#› Data Manipulation & Regex. PHP Workshop ‹#› What..? Often in PHP we have to get data from files, or maybe through forms from a user.
Nael Alian Introduction to PHP
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
CONTROL STRUCTURE The if, elseif, and else & switch Statements 1.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
PHP: A RRAYS, S TRINGS, AND F ILES CSCI 297 Scripting Languages - Day Three.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
JavaScript, Fourth Edition
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
More Strings CS303E: Elements of Computers and Programming.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
PHP-5- Working with Files and Directories. Reading Files PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Decision Making and Branching
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
JavaScript, Sixth Edition
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
 Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
Expressions and Control Flow in PHP
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Expressions and Control Flow in JavaScript
ITM 352 Flow-Control: Loops
More Selections BIS1523 – Lecture 9.
Chapter 8 JavaScript: Control Statements, Part 2
PHP.
Logical Operations In Matlab.
String functions
Data Manipulation & Regex
Basics.
2.6 The if/else Selection Structure
String functions
Presentation transcript:

PHP Controlling Program Flow Mohammed M. Hassoun 2012

Controlling Program Flow

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'; } ?>

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:

<?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'; } ?>

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.

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++; } ?>

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); ?>

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. " "; } ?>

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

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

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

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); ?>

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 = echo ' at ', $str); ?>

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.

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); ?>

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); ?>

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); ?>

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); ?>

Thank You