PHP If Condition
Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008
0
The If Statement
This statement executes a piece of code only when a condition is true.
Syntax
- if (condition) code to be executed if condition is true;
<html>
<body>
<?php
$d=date(”D”);
if ($d==”Fri”) echo “Today is Friday!”;
?>
</body>
</html>
The if…else Statement
This is a two way condition evaluation, in which there are yes and no both lead to different code block.
We just add one else condition in the above if statement.
Syntax
- if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
<html>
<body>
<?php
$d=date(”D”); if ($d==”Fri”)
echo “Today is Friday!”; else
echo “Today is not Friday!”;
?>
</body>
</html>
If more than one line should be executed, then the lines should be enclosed within curly braces:
<body>
<?php
$d=date(”D”);
if ($d==”Fri”)
{
echo “Hello!<br />”;
echo “Today is Friday!”;
}
?>
</body>
</html>
The if…elseif….else Statement
This construct is used when there are more conditions than just true or false.
When PHP evaluates If…elseif…else statement it first sees if the If statement is true. If that test comes out to be false it then checks the first elseif statement.
If then also the result comes out to be false it will check the next elseif statement, if there exists any more otherwise, it will evaluate the else segment, if one exists.
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;
<html>
<body>
<?php
$d=date(”D”); if ($d==”Fri”)
echo “Today is Friday!”; elseif ($d==”Sun”)
echo “Today is Sunday!”; else
echo “Today is neither Friday nor Sunday!”;
?>
</body>
</html>
