Condition Statement in PHP
Program is a set of instructions for computer to execute. It is important to tell the computer when to execute an instruction and when not to. Thus, the condition statement has become a very important code in programming language. A proper planned condition statement may make the computer execute "WISELY". An artificial intelligent nothing but a bunch of condition statement to help computer to decide the next move.Type of condition statement in PHP
- If (condition) { ….. }
- If (condition) { ….. } else { ….. }
- If (condition) { ….. } else if(condition) { ….. } else { ….. }
- switch (var) { case x: …..; break; case y: …..; break; }
If (condition) { ….. }
This is the simplest form of conditional statement. This statement will check whether the condition is TRUE to execute block of codes within the curly brace.
<?php
$age = $_POST['age'];
if($age>18){
echo "You are adult!";
}
}
?>
If (condition) { ….. } else { ….. }
This condition statement contain two possible states (TRUE or FALSE). This statement will check whether the condition is TRUE to execute the first block of code and otherwise execute the second block of code in the else block.
<?php
$age = $_POST['age'];
if($age>18){
echo "You are adult!";
}else{
echo "You are just a kid";
}
}else{
echo "You are just a kid";
}
?>
If (condition) { ….. } else if(condition) { ….. } else { ….. }
This condition statement contain multiple possible states. If the first condition is true, the first block of codes will be executed Otherwise, if second condition is met, the second block of codes will be executed.
<?php
$age = $_POST['age'];
if($age>0 and $age<=1){
echo "You are Infant!";
}else if($age>1 and $age<=3){
echo "You are toddler";
}else if($age>3 and $age<=18){
echo "You are child";
}else if($age>18){
echo "You are adult";
}
}else if($age>1 and $age<=3){
echo "You are toddler";
}else if($age>3 and $age<=18){
echo "You are child";
}else if($age>18){
echo "You are adult";
}
?>
switch (var) { case x: …..; break; case y: …..; break; }
This condition statement contain multiple possible states. If any of this condition is true, the case block of that particular code will be execute.
<?php
$menuOption = $_POST['option'];
switch($menuOption){
case 1: echo 'Show Record';
break;
case 2: echo 'Add Record';
break;
case 3: echo 'Delete Record';
break;
case 4: echo 'Update Record';
break;
default: echo 'Invalid Option';
break;
}
?>
No comments:
Post a Comment