2.Program Flow

1. Switching Flow
-Evaluates condition and changes their behavior accordingly 
-Facility to make decisions makes your PHP pages dynamic 
-Capable of changing their output according to circumstances

2. The if Statement
Syntax
if (expression) { // code to execute if the expression evaluates to true
Example
<?php 
$x = “10";
$y = 10;  
if ( $x == $y ) { 
 print “same"; 
}?> 
//result:  same


3. The if Statement – with an else clause
Syntax
if (expression) { // code to execute if the expression evaluates to true } 
else { // code to execute in all other cases }
Example
<?php 
$x = “10"; $y = 10;  
if ( $x === $y ) 
{ echo “same"; }
else {echo “different”  }
?> //result:  different


4. The if Statement – with an else if clause else
Syntax
if ( expression ) 
{ // code to execute if the expression evaluates to true } 
else if ( another expression ) 
{ // code to execute if the previous expression failed // and this one evaluates to true } 
else 
{ // code to execute in all other cases} 
Example
<?php 
$x = “10"; $y = 10;  
if ( $x === $y ) 
{  echo “same type and value"; }
else if ($x == $y)
{ echo “same value"; }
else echo “different” 
}?> //result:  same value


5. The switch Statement
Syntax
switch (expression) 

case result1: // execute this if expression equivalent to result1 
break; 
case result2: // execute this if expression equivalent to result2
break; 
default: // execute this if no break statement has been encountered until here

Example
<?php 
$feeling = “sad"; 
switch ( $feeling ) { 
  case “happy": 
print “I am glad that you are happy"; 
break; 
case “sad": 
print “I am sorry that you are sad"; 
break; 
default: 
print "Please take a moment to pray";  
}  ?>

6. Using the ? Operator
Syntax
(expression) ?if_expression_is_true:if_expression_is_false; 


Example
<?php 
$day = “smile";
$good = “Happy";
$bad = “frown";
$text = ( $day==“smile" )?$good:$bad;
print "$text";  
?> 


7. The while Statement
Syntax
while ( expression ) { // do something } 
Example
<?php 
$counter = 1; 
while ( $counter <= 12 ) {
print "$counter times 2 is ".($counter*2)."<br />"; 
$counter++; 

?> 


8. The do...while Statement 
Syntax
do { // code to be executed } while (expression); 


Example
<?php 
$x = 1; 
do { 
print "Execution number: $x<br />\n"; 
$x++; 
} while ( $x > 200 && $x < 400 ); 
?> 


9. The for Statement
Syntax
for ( initialization expression; test expression; modification expression ) { // code to be executed } 


Example
<?php 
for ( $count=1; $count<=12; $count++ ) 
{
print "$count times 2 is".($count*2)."<br />"; 
}
?> 


10. Breaking Out of Loops using break
Example
<?php 
for ( $counter=1; $counter <= 10; $counter++ ) { 
if ( $counter == 0 ) 
{ break;}
$temp = 4000/$counter; 
print "4000 divided by $counter is.. $temp<br />"; 

?> 

No comments:

Post a Comment