Monday, June 17, 2013

php switch statment

php switch
In this lesson we will talk about switch statment and what does it mean and what it can do, before we start write the code let us give an example first, we want to make a calculator that can do this operations (+,-,*,/)
we can write the code like this
<?php
$n1 = 5 ;
$n2 = 7 ;
$operation = "/" ;
$result = " " ;
if ( $operation == '+') { 
echo "$n1" +  "$n2" ;
}
 if ( $operation == '-') { 
echo "$n1" -  "$n2" ;
}
if ( $operation == '*') { 
echo "$n1" *  "$n2" ;
}
if ( $operation == '/') { 
echo "$n1" /  "$n2" ;
}
?> 
We will see on the screen 12, But if we use php switch statment it will be like this
<?php
$n1 = 5 ;
$n2 = 7 ;
$operation = "+" ;

switch ($operation) { 
case "+" :
echo "$n1"+"$n2" ;
break;
case "-" :
echo "$n1"-"$n2" ;
break;
case "*" :
echo "$n1"*"$n2" ;
break;
case "/" :
echo "$n1"/"$n2" ;
break;
}
?>
php switch

And we will see 12 in the screen but without using if else statement, This was the php switch statement
 I hope you enjoy the lesson, and see you next time

Share This!



No comments :

Post a Comment