module2-ControlSttm.pdf - Module 2 Condition Statement...

This preview shows page 1 - 4 out of 21 pages.

Module 2: Condition Statement & Loops Condition Statement if if/else switch while, do/while, for, foreach include()/require() CS 85: PHP PROGRAMMING Santa Monica College Computer Science & Information Systems Dept.
Up to this point all the code you have written only contain only simple statements. These PHP scripts were interpreted line by line from top to bottom, with each line being executed. PHP like many other programming languages allow you to make decisions in your code that changes the order of execution in your code, thus controlling the flow of code. This is important to allow a change of outcome of your code depending on some condition or results that will determine which statement should be executed. For example, you have a game app that changes activities based on a child age. Then if a child is between age 2 and 5, run this block of code for the age appropriate games. If the child is over 5, run this other block of code for more advance age appropriate games. The most widely used commonly see condition statement is the if statement. if statement Conditional structures are used to control which statements get executed. They are composed of three fundamental elements: if statements; elseif statements if else statements The structure begins with an if clause, which is composed of the word "if" followed by a true/false statement in parentheses ( … condition statement ). The subsequent code will be contained in a block, denoted by curly braces { … code… }. The braces can be omitted if only one line will follow the if statement. elseif and else clauses can be added after the if clause to test for different statements and execute different blocks of code. If statement structure: if (conditional expression) statements; The if statement is composed of three parts: the keyword if, a conditional expression enclosed within parentheses, and the executable statements. Note that the conditional expression must be enclosed within parentheses. The if clause says "If this statement is true, I want the program to execute the following statements. If it is false, then ignore these statements." In technical terms, it works like this: When an if statement is encountered, the true/false statement in parentheses is evaluated. If the statement is found to be true, the subsequent block of code contained in curly braces is executed. However, if the statement is found to be false, the program skips those lines and executes the next non-blank line. Following the if clause are two optional clauses: else and elseif. The elseif (or else if) clause says "If the last statement was false, let's see, if this statement is true. If it is, execute the following code. If it isn't, then skip it." elseif statements are only evaluated when the preceding if