Conditional Statements
Previous Page | Home Page | Next Page |
---|
In PHP we have the following conditional statements:
The if Statement
We can use the if statement to executesome code only if a specified condition is true.
Syntax
if (condition) code to be executed ifcondition is true;
<html> <body> <?php $d=1; if ($d==1) echo "Valid IfCondition"; ?> </body> </html>
|
The if...else Statement
We can usethe if....else statement toexecute some code if a condition is true and another code if acondition is false.
Syntax
if (condition) { code to be executed if condition istrue; } else { code to be executed if condition isfalse; }
|
Example
<html><body> <?php $d=1; if ($d==2) { echo "IF Condition"; } else { echo "Else Condition"; } ?> </body></html>
|
The if...elseif....else Statement
We can usethe if....elseif...elsestatement to select one of several blocks of code to be executed.
Syntax
if (condition) { code to be executed if condition istrue; } elseif (condition) { code to be executed if condition istrue; } else { code to be executed if condition isfalse; }
|
Example
<html><body> <?php $d=2; if ($d==3) { echo "Number 1"; } elseif ($d==2) { echo"Number 2"; } else { echo"Number 3"; } ?> </body></html>
|
Output
Number 2
Switch Statement
We can use the switch statement toselect one of many blocks of code to be executed.
Syntax
switch (label) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is differentfrom both label1 and label2; }
|
Example
<html><body> <?php $x=1; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body></html> |
Previous Page | Home Page | Next Page |
---|