Lesson 4: Control Structures - TOP10

Lesson 4: Control Structures

Most scripts evaluate conditions and change their behavior accordingly. The capability to make decisions makes your PHP pages dynamic, able to change their output according to circumstances. Like most programming languages, PHP allows you to do this with an if statement. 

1. Conditional Statements

 - if Statement 
An if statement is a way of controlling the execution of a statement that follows it (that is, a single statement or a block of code inside braces). The if statement evaluates an expression between parentheses. If this expression results in a true value, the statement is executed. Otherwise, the statement is skipped entirely.
 Syntax: 
   if ( expression ) // Single Statement
     or if ( expression ) { //Single Statement or Multiple Statements 
      } or if ( expression ) : //Single Statement or Multiple Statements 
    endif; 

Example:
<?php
    $st = "hello"; if ( $st == "hello" ) { print "Hello everybody in class.";

?> 

You use the comparison operator == to compare the variable $st with the string "hello". If they match, the expression evaluates to true, and the code block below the if statement is executed. When you access this script through your Web browser, it produces the following: Hello everybody in class.

- Using the else Clause with the if Statement 

When working with the if statement, you will often want to define an alternative block of code that should be executed if the expression you are testing evaluates to false. You can do this by adding else to the if statement followed by a further block of code: if ( expression ) // Single Statement else // Single Statement Or if ( expression ) { // Single Statement or Multiple Statements

} else { // Single Statement or Multiple Statements } Or if ( expression ) : // Single Statement or Multiple Statements else: // Single Statement or Multiple Statements 
endif;

Example: When you access this script through your Web browser, it produces the following: Not say hello to everybody in class.

- Using the elseif Clause with the if Statement

You can use an if...elseif...else construct to test multiple expressions before offering a default block of code: 
if ( expression ) // Single Statement 
elseif (another expression) // Single Statement 
[ else // Single Statement ] Or if ( expression ) { // Single Statement or Multiple Statements 
} elseif (another expression) { // Single Statement or Multiple Statements 
[ else { // Single Statement or Multiple Statements } ]
 Or if ( expression ) : // Single Statement or Multiple Statements elseif (another expression) : // Single Statement or Multiple Statements [ else : // Single Statement or Multiple Statements ] endif;

If the first expression does not evaluate to true, the first block of code is ignored. The elseif clause then causes another expression to be evaluated. Once again, if this expression evaluates to true, the second block of code is executed. Otherwise, the block of code associated with the else clause is executed. You can include as many elseif clauses as you want, and if you don't need a default action, you can omit the else clause. The elseif clause can also be written as two separate words (else if). Example: Once again, $st holds a string, " Hi ". This is not equal to "Hello", so the first block is ignored. The elseif clause tests for equivalence between the contents of $st and the value "Hi", which evaluates to true. This block of code is therefore executed and the else block is ignored. When you access this script through your Web browser, it produces the following: Hi everybody in class. - switch Statement The switch statement is an alternative way of changing program flow according to the evaluation of an expression. There are some key differences between the switch and if statements. Using the if statement in conjunction with elseif, you can evaluate multiple expressions. The switch statement evaluates only one expression, executing different code according to the result of that expression, as long as the expression evaluates to a simple type (a number, a string, or a Boolean). The result of an expression evaluated as part of an if statement is read as either true or false. The expression of a switch statement yields a result that is tested against any number of values: switch ( expression ) { case result1: // execute this if expression results in result1 break; case result2: // execute this if expression results in result2 break; default: // execute this if no break statement // has been encountered hitherto } Or switch ( expression ) : case result1: // execute this if expression results in result1 break; case result2: // execute this if expression results in result2

break;
default:
// execute this if no break statement
// has been encountered hitherto
endswitch;
The switch statement's expression is often simply a variable. Within the switch statement's
block of code, you find a number of case statements. Each of these tests a value against the
result of the switch statement's expression. If these are equivalent, the code after the case
statement is executed. The break statement ends execution of the switch statement altogether.
If this is left out, the next case statement's expression is evaluated. If the optional default
statement is reached, its code is executed.
Don't forget to include a break statement at the end of any code that will be
executed as part of a case statement. Without break, the program flow will
continue to the next case statement and ultimately to the default statement. In
most cases, this will not be the behavior that you are expecting.
Example:
<?php
$st = "Hi";
switch($st)
{
case "Hello":
echo "Hello everybody in class.";break;
case "Hi":
echo "Hi everybody in class.";break;
default:
echo "Not say hello or hi to everybody in class.";
}
?>
Once again, The $st variable is initialized to "Hi". The switch statement uses this variable as its
expression. The first case statement tests for equivalence between "Hello" and the value of $st.
There is no match, so script execution moves on to the second case statement. The string "Hi" is
equivalent to the value of $st, so this block of code is executed. The break statement ends the
process.
When you access this script through your Web browser, it produces the following:
Hi everybody in class.
- Ternary Operator
The ? or ternary operator is similar to the if statement but returns a value derived from one
of two expressions separated by a colon. This construct will provide you with three parts of the
whole, hence the name "ternary." Which expression is used to generate the value returned
depends on the result of a test expression:
( expression )?returned_if_expression_is_true:returned_if_expression_is_false;
If the test expression evaluates to true, the result of the second expression is returned;
otherwise, the value of the third expression is returned.
Example:
<?php
$st = "Hi";

$result = ($st=="Hello") ? "Hello everybody in class." : "Hi everybody in class."; print $result; ?> $st is set to "Hi". $st is tested for equivalence to the string "happy" but this test returns false, the result is the third of the three expressions is returned. When you access this script through your Web browser, it produces the following: Hi everybody in class. 2. Looping Statements So far we've looked at decisions that a script can make about what code to execute. Scripts can also decide how many times to execute a block of code. Loop statements are designed to enable you to achieve repetitive tasks. Almost without exception, a loop continues to operate until a condition is achieved, or you explicitly choose to exit the loop. - while Statement The while statement looks similar in structure to a basic if statement: while ( expression ) { // do something } Or while ( expression ) : // do something endwhile; As long as a while statement's expression evaluates to true, the code block is executed over and over again. Each execution of the code block in a loop is called an iteration. Within the block, you usually change something that affects the while statement's expression; otherwise, your loop continues indefinitely. Example: "; $counter++; } ?> In this example, we initialize a variable $counter. The while statement tests the $counter variable. As long as the integer that $counter contains is less than or equal to 10, the loop continues to run. Within the while statement's code block, the value contained by $counter is multiplied by two, and the result is printed to the browser. Then increments $counter. This last stage is extremely important. If you were to forget to change $counter, the while expression would never resolve to false, and the loop would never end. When you access this script through your Web browser, it produces the following: 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10

2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 2 * 10 = 20
 - do...while Statement Do…while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). do { // code to be executed } while ( expression ); The test expression of a do...while statement should always end with a semicolon. This statement might be useful if you want the code block to be executed at least once even if the while expression evaluates to false. Example: \n"; $num++; } while ( $num > 10 ); ?> The do...while statement tests whether the variable $num contains a value that is greater than 10. We have initialized $num to 1, so this expression returns false. Nonetheless, the code block is executed before the expression is evaluated, so the statement will print a single line to the browser. When you access this script through your Web browser, it produces the following: Execution number: 1 - for Statement The for statement is used to control a loop within your PHP program. It works like the while and do..while statements that we discussed in previous sections. The for statement tests an expression. If that expression is true the program will execute the task within the loop. Here is the basic code. for (initialize variable exp; test expression; modify variable exp) // Single Statement Or for (initialize variable exp; test expression; modify variable exp){ // Single Statement or Multiple Statements } Or for (initialize variable exp; test expression; modify variable exp):

// Single Statement or Multiple Statements endfor; Example: for ($number = 1; $number < 11; $number++) { echo "$number
"; } The above example behaves the same as the while and do..while statements in the previous sections. However, if you compare these statements you will notice a few differences. for() The for statement begins with a for in front of two parenthesis. Inside the parenthesis are the three expressions that form the first part of the for statememt. $number = 1; (initialize variable expression;) The for statement begins with a for in front of two parenthesis. Inside the parenthesis $number < 11; (test expression;) This is the control part of the loop statement. The loop will repeat as long as the test expression remains true. In the example the loop will continue until the $number variable is no longer less than 11. $number++ (modify variable expression) This expression increases the counter variable by 1. As with the while and do..while statements, this is a necessary part of the for statement. Without it the loop cannot change the value of the $number counter variable causing the loop to repeat indefinitely. { echo "$number
"; } ( { //Statements; } ) This is the part of the code that will be executed each time through the for statement as long as the test expression remains true. In the example the program will print the current value of the $number variable and the HTML
code to the web browser. Notice the differece from the while and do..while statements. In those statements the code that increased (changed) the value of the counter variable was included in this { do this } part of the code. But in the for statement it is within the parenthesis. When you access this script through your Web browser, it produces the following: 1 2 3 4 5 6 7 8 9 10 - break Statement The Break statement terminates the current for, foreach, while, do-while or switch structure and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.

The first example below show how to use the Break statement: Example of using the Break statement:
"; for ($i=0; $i<=10; $i++) { if ($i==3){ break; } echo "The number is ".$i; echo "
"; } ?> We use an if statement to test the value of $i. If it is equal to 3, the break statement immediately ends execution of the code block, and program flow continues after the for statement. When you access this script through your Web browser, it produces the following: Example of using the Break statement: The number is 0 The number is 1 The number is 2 The second example below show how to use the Break statement: One more example of using the Break statement:
"; $i = 0; $j = 0; while ($i < 10) { while ($j < 10) { if ($j == 5) {break 1;} // breaks out of one while loop if break=2 it will //breaks out of two while loops $j++; } $i++; } echo "The first number is ".$i."
"; echo "The second number is ".$j."
"; ?> When you access this script through your Web browser, it produces the following: One more example of using the Break statement: The first number is 10 The second number is 5 If break=2 the result will be: One more example of using the Break statement: The first number is 0 The second number is 5

- continue Statement

The Continue statement terminates execution of the block of statements in a looping structures and continues execution of the loop with the next iteration: Example: Example of using the Continue statement:
"; for ($i=0; $i<=10; $i++) { if ($i==3){continue;} echo "The number is ".$i; echo "
"; } ?> If the $i variable is equivalent to 3, the iteration is skipped, and continue execution at the condition evaluation and then the beginning of the next iteration. When you access this script through your Web browser, it produces the following: Example of using the Continue statement: The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 - Nesting Loops Nesting Loops are Loop statements can contain other loop statements. Example: "; for ( $y=1; $y<=12; $y++ ) { print ""; for ( $x=1; $x<=12; $x++ ) { print ""; print ($x*$y); print ""; } print ""; } print ""; ?> Before we examine the for loops, let's take a closer look at the statement: print "\n"; Notice that we have used the backslash character (\) before each of the quotation marks within the string. This is necessary in order to tell the PHP engine that we wish to use the quotation mark character, rather than interpret it as the beginning or end of a string. If we did not do this, the statement would not make sense to the engine, which would read it as a string followed by a number followed by another string. This would generate an error. The outer for statement initializes a variable called $y, setting its starting value to 1. 
It defines an expression that verifies that $y is less than or equal to 12 and defines the increment for $y. For each iteration, the code block prints a tr (table row) HTML element and defines another for statement. This inner loop initializes a variable called $x and defines expressions along the same lines as for the outer loop. For each iteration, the inner loop prints a td (table cell) element to the browser, as well as the result of $x multiplied by $y. We close the table cell. After the inner loop has finished, we fall back through to the outer loop, where we close the table row, ready for the process to begin again. When the outer loop has finished, the result is a neatly formatted multiplication table. We wrap things up by closing the table.’ When you access this script through your Web browser, it produces the following:




Previous
Next Post »