Pages

Saturday, 16 June 2012

if ,else and statements in PHP

The If Statement:-
Syntax:-------------------------------

if (condition) code to be executed if condition is true;
for example:-

<?php
$d=date("D");
 if ($d=="Fri") echo "Have a very very nice weekend!";
?>


The output of above code will be -  Have a very very nice weekend!
This result will printed only if day is friday not on any other day.
So as to display a different output we use the else statement along with
the if statement. 
Here is the syntax for if-else statement.


if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}



so, we can write code as-->



<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
else
{
echo "Have a nice day!";
}
?>

The output if the day is friday will be-
Have a very very nice weekend! 

The output if the day is not friday will be-
Have a nice day!



Note:-we have already discussed simple if-else

but nested if-else facility is also available in PHP

syntax==>for nested if-else-

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;
}

Possible example may be:-
<?php
$d=date("D");
if ($d=="Fri")
{
 echo "Have a nice weekend!";  //if day is friday this(<--) will be printed
}
elseif ($d=="Sun")
{
  echo "Have a nice Sunday!";   //if day is sunday
}
else
{
  echo "Have a nice day!";    //any other day except sunday and friady
}
?>

***************************









 

No comments:

Post a Comment