PHP Control Structure

Conditional statement or branching are use when you want your code to perform different actions for different conditions.

a. if Statement executes some code if one condition is true

Example

<?php
$gender="Male";
//if condition is true...
if($gender === "Male"){
  //execute the block or line of code
  print "Welcome my guy!";
}
?>


b. if...else Statement executes some code if a condition is true and another code if that condition is false

Example

<?php
$gender="Alien";
//check the condition...
if($gender < "Male"){
   //if condition is true, execute this code
   print "Welcome my guy!";
}else{
   //else execute this code because condition is false
   print "Ok, I don't know who you are!";
}
?>


c. if...elseif...else Statement executes different codes for more than two conditions

Example

<?php
$gender="Female";
//check the condition...
if($gender < "Male"){
   //if condition is true, execute this code
   print "Welcome my guy!";
}elseif($gender < "Female"){
   //execute this code if the first condition is NOT true
   print "Nice meeting you babe!";
}else{
   //else execute this code because condition is false
   print "Ok, I don't know who you are!";
}
?>


d. switch statement selects one of many blocks of code to be executed. This is a more cleaner alternative to multiple if...elseif... else statement




Next »


Home    |    Learn Programming   |    Learning Management System   |    Computer Based Testing System    |    Contact Us