lecture 4 conditional-code (Day-2)

advertisement
USING CONDITIONAL CODE
AMIR KHNAZADA
Else if Statement
 If you want to execute some code if one of several conditions
are true use the else if statement.
 else if statement is used as extension of "If" structure if the
condition fails then it executes another "If" condition to
execute the code segment under the "else if" statement.
 Syntax:
• if (condition)
code to be executed if condition is true;
• elseif (condition)
code to be executed if condition is true;
• else
code to be executed if condition is false;
Else if Statement
 <?php
$c = 10;
$d = 10;
if ($c > $d) {
echo "c is bigger than d";
}
elseif ($c==$d) {
echo "c is equal to d";
}
else {
echo "d is smaller than c"; } ?>
Result: c is equal to d
In the above example the if the condition "$c>$d" is true then the
message "c is bigger than d" is displayed, else the condition in the else if
that is "$c==$d" is evaluated if it is true the message "c is equal to d" is
displayed otherwise "d is smaller than c" is displayed
Switch Statement
 The Switch case statement is used to compare a variable or
expression to different values based on which a set of code is
executed.
 If you want to select one of many blocks of code to be
executed, use the Switch statement.
 The switch statement is used to avoid long blocks of
if..elseif..else code.
Switch Statement
 Syntax:
switch ( <variable> ) {
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;...
default:
Code to execute if <variable> does not equal the value
following any of the cases
break;
}
Else if Statement
 <?php
$x=2;
switch ($x) {
case 1:
echo “Number 1”;
break;
case 2:
echo “Number 2”;
break;
default:
echo “No number between 1 and 3”;
}
?>
Switch Statement
 The condition of a switch statement is a value. The case says
that if it has the value of whatever is after that case then do
whatever follows the colon.
 Break is a keyword that breaks out of the code block, usually
surrounded by braces, which it is in. In this case, break
prevents the program from falling through and executing the
code in all the other case statements
Switch Statement
 It isn’t legal to use case:
$a = 10;
$b = 10;
$c = 20;
like this: switch ( $a ) {
case $b:
/* Code */ break;
case $c:
/* Code */ break;
default:
/* Code */ break; }
Switch Statement
 The default case is optional, but it is wise to include it as it
handles any unexpected cases. It can be useful to put some
kind of output to alert you to the code entering the default
case if you don’t expect it to.
 Switch statements serve as a simple way to write long if
statements when the requirements are met.
Download