PHP Basics – Conditional Statements

1. Simple If Condition

<?php
/*
* Author : Anthoniraj
* Created on Jan 8, 2008
* Program Name : 06ifcondition.php
*/
$a = 10;
$b = 20;
if($a > $b)
{
echo “A is bigger than B”;
}
echo “The value of A is $a<br>”;
echo “The value of B is $b”;
?>

2. If-Else Condition

<?php
/*
* Author : Anthoniraj
* Created on Jan 8, 2008
* Program Name : 07ifelse.php
*/
$a = 10;
$b = 20;
if($a > $b)
{
echo “A is bigger than B”;
}
else
{
echo “A is less than B <br>”;
}
echo “The value of A is $a<br>”;
echo “The value of B is $b”;
?>

3.Nested If-Else

<?php
/*
* Author : Anthoniraj
* Created on Jan 8, 2008
* Program Name : 08elseif.php
*/

//Simple Example
$a = 10;
$b = 30;
if($a > $b)
{
echo “A is bigger than B”;
}
else if ($a < $b)
{
echo “A is less than B <br>”;
}
else
{
echo “A is equal to B”;
}

//Another example – University Grade System
/*
* S grade (10 points)=> 90 to 100
* A grade (9 points) => 80 to 89.9
* B grade (8 points) => 70 to 79.9
* C grade (7 points) => 60 to 69.9
* D grade (6 points) => 55 to 59.9
* E grade (5 points) => 50 to 44.9
* F (fail)(0 points) => below 50 (<50)
*/
$mark = 75;
if(($mark>=90) && ($mark<=100))
{
echo “You have got S grade “;
}
elseif(($mark>=80) && ($mark<=89.9))
{
echo “You have got A grade “;
}
elseif(($mark>=70) && ($mark<=79.9))
{
echo “You have got B grade “;
}
elseif(($mark>=60) && ($mark<=69.9))
{
echo “You have got C grade “;
}
elseif(($mark>=55) && ($mark<=59.9))
{
echo “You have got D grade “;
}
elseif(($mark>=50) && ($mark<=54.9))
{
echo “You have got E grade “;
}
else
{
echo “Sorry , you are fail in this subject”;
}
?>

4.Alternate Syntax for If-Else in PHP

<?php
/*
* Author : Anthoniraj
* Created on Jan 8, 2008
* Program Name : 10newelseif.php
*/
$c=30;
if($c>20) : //Use colon instead of opening braces
echo “C is a Big Number”;
else :
echo “C is a Small Number”;
endif; //finish with semi colon

?>

Leave a Response