// phpShack / PHP & MySQL Tutorials / PHP If/Else
 

Navigation





 

PHP If/Else

In PHP you sometimes need your script to run different code if a condition it true or false. This is where the if/else statements come in to play. There is also a elseif statement that you may use when multiple conditions are true, we will look at examples of all this in a bit. If/Else statements can be troubling later if you don't comment them well, especially when you can a lot of them together, you go back later and can't remember what does what. So please be sure to comment your if/else statements well, as you should all of you code.

Basic If/Else Statement:

PHP Code Example:
<?
// Use the curly braces if your code is more than one line
if (condition) {
// here is your code if the condition is true
// line two of your code
} else {
// here is your code if the condition is false
// line two of your code
}
?>

PHP Code Example:
<?
// You don't have to use the curly braces if your code is one line
if (condition)
// here is your code if the condition is true
else
// here is your code if the condition is false
?>

Now lets look at a real example of the if/else in action by evaluating a condition.

Example If/Else Statement:
PHP Code Example:
<?
$a 
5// Set $a equal to 5
$b 2// Set $b equal to 2

if ($a $b) { // If $a is greater than $b
// here is your code if the condition is true
echo "a($a) is greater than b($b)!";
} else {
// here is your code if the condition is false
echo "a($a) is not greater than b($b) so the expression is false";
}
?>

Now lets look at the elseif statement where we will evaluate multiple expressions.

Basic elseif Statement:
PHP Code Example:
<?
// Use the curly braces if your code is more than one line
if (condition)
// here is your code if the condition is true
elseif (condition)
// here is your code if the condition is true
else
// here is your code if the condition is false
?>


Example elseif Statement:
PHP Code Example:
<?
$number 
4// Set $number equal to 4
// Use the curly braces if your code is more than one line
if ($number == 5)
// here is your code if the condition is true
echo "Your number is 5";
elseif (
$number == 2)
// here is your code if the condition is true
echo "Your number is 2";
else
// here is your code if the condition is false
echo "Your number is not 5 or 2";
?>