Nov 06, 2013, by admin
PHP If…Else Control Statements
When we write code in any language, we perform different actions for different decisions. Like other languages PHP script is built out of a series of control statements. The control statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing or an empty statement. In PHP we have the following conditional statements:
if statement – We use this control statement to execute some code only if a specified condition is true.
if…else statement – We use this control statement to execute some code if a condition is true and another code if the condition is false.
if…elseif….else statement – We use this control statement to select one of several blocks of code to be executed
switch statement – We use this control statement to select one of many blocks of code to be executed
The if Statement
Use the if statement to execute some code only if a specified condition is true.
The expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE – it’ll ignore it
if (expr) statement
if (condition) code to be executed if condition is true;
The following example would display ” A is bigger than B” if $a is bigger than $b:
<html> <body> <?php if ($a > $b) echo “A is bigger than B”; ?> </body> </html>
The if…else Statement
elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:
<html> <body> <?php if ($a > $b) { echo “a is bigger than b”; } elseif ($a == $b) { echo “a is equal to b”; } else { echo “a is smaller than b”; } ?> </body> </html>
Use the if….elseif…else statement to select one of several blocks of code to be executed.
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;