In this tutorial we will discuss about various ways to write if else condition with basic example.
If Statement Syntax :
if (condition){
code to be executed if condition is true;
}
Sample Code :
$str1 = "Ram";
$str2 = 'Sita';
if($str1 == 'Ram'){
echo "Ram is a boy";
}
if($str2 == 'Sita'){
echo "Sita is a girl";
}
$dob = date("d/m/Y"); // Later we will discuss about date function in details..
// Date function returns current date.
//d- current date(1-31) , m- current month in number (1 to 12) & Y – Current Year in 4 digit eg : 2011,
//y- Current year in 2 digit ( eg : 11 )
if($dob == "23/07/2011"){
echo "Happy birthday to you";
// Consider today's date is 23/07/2011
}
?>
Ram is a boy
Sita is a girl
Happy birthday to you
if..else Statement
Syntax :
if (condition){
code to be executed if condition is true;
}else{
code to be executed if condition is false;
}
Sample Code :
1. Check whether number is odd or even
$number = 5;
if($number % 2 == 0){
echo "$number is even number";
}
else{
echo "$number is odd number";
}
?>
2. Check leap year
$year = 2011;
if ( $year % 400 == 0 OR ( $year %100 !=0 AND $year%4==0)){
echo "$year is leap year";
}
else{
echo "$year is not leap year";
}
?>
3. Find the greater between 2 numbers
$num1 = 10;
$num2 = 20;
if($num1>$num2){
echo "$num1 is big";
}
else{
echo "$num2 is big";
}
?>
if…elseif….else 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;
}
Sample Code :
4. find the biggest among 3 numbers
$a=10;
$b=20;
$c=15;
if($a>$b AND $a>$c){
echo "$a is biggest";
}
elseif($b>$c){
echo "$b is biggest"; }else{ echo "$c is biggest";
}
?>