PHP if...elseif...else Conditional Statements Tutorial
PHP if...elseif...else Conditional Statements
The whole idea of website development using PHP is to be able to access code based on conditions. The following is a tutorial that will explain how to use PHP conditions to execute certain code based on actions.
In PHP the following conditional statements apply:
The PHP if Statement
Use the if statement to execute certain code when a specified condition is true.
Syntax: if (condition) {code to be executed if condition is true;}
The following example will output "one hundred" if the value of $number is 100:
<html>
<body>
<?php
$number=100;
if ($number == 100) echo "one hundred";
?>
</body>
</html>
The PHP if...else Statement
Use the if...else statement to execute certain code if a condition is true and another code if a condition is false.
Syntax:
if (condition)
{code to be executed if condition is true;}
else
{code to be executed if condition is false;}
Example:
The following example will output "one hundred" if the variables value is 100, otherwise it will output "your value is not 100":
<html>
<body>
<?php
$number=100;
if ($number == 100)
{echo "one hundred";}
else
{echo "your value is not 100";}
?>
</body>
</html>
I personally recommend always using curly braces when doing if statements to get in the habit. This being said the only time you have to use them is if you are running more than one line of code in an if statement:
<html>
<body>
<?php
$number=100;
if ($number == 100)
{
echo "one hundred";
echo "is the answer";
}
else
{
echo "your value is not 100";
echo "sorry";
}
?>
</body>
</html>
The PHP if...elseif...else Statement
Use the if...elseif...else statement to select one of many 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;}
Example:
The following example will output "fifty" if the current value is 50, and "one hundred" if the current value is 100. Otherwise it will output "your value is not 50 or 100":
<html>
<body>
<?php
$number=100;
if ($number == 50)
{
echo "fifty";
}
elseif ($number == 100)
{
echo "one hundred";
}
else
{
echo "your value is not 50 or 100";
}
?>
</body>
</html>
