This section contains detail about IF-Else Conditional Statement In PHP .
IF-Else Conditional Statement In PHP
Conditional Statements are used to carry out actions based on condition. If-Else is also a conditional statement used to perform different action according to different conditions.
In PHP, We have the following conditional statement :
- if statement
- if...else statement
- if...elseif....else statement
Lets discuss these one by one:
if statement
This statement executes code if provided condition is true. If condition failed, it jumps to the statement next to if block. The syntax is given below :
if (condition) code for execution, if provided condition is true;
Given below a example to demonstrate the above :
$person = "John"; if ( $person == "John" ) { echo "Welcome John!<br />"; } echo "You are not John!";
If person is John, it will display following message :
Welcome John!
If person is not John, it will show :
You are not John!
if...else statement
This statement executes 'if block' if condition is "True" ,otherwise it executes 'else' block . Syntax is given below :
if (condition) code for execution, if provided condition is true; else code for execution, if provided condition is false;
Given below the example:
<html> <body> <?php $day=date("D"); if ($day=="Fri") echo "Today is Friday!"; else echo "Today is not Friday!"; ?> </body> </html>
if...elseif....else statement
First, It checks condition in 'if' block. If it is true, it will execute 'if block'. If false, it will check elseif block, if elsif is true-it will execute elseif block. If it is also false, it will execute else block. Given below it's syntax & example :
if (condition) code for execution, if provided condition is true; elseif (condition) code for execution, if provided condition is true; else code for execution, if provided conditions are false;
Example for above code is given below :
<html> <body> <?php $day=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>
[ 0 ] Comments