If...Else statements

  • Description : By the end of the tutorial you will understand how important and useful If..else loops are!
  • Language : PHP
  • Date Added : 13th October, 2009
Bookmark and Share

If statements can be used to control the flow of your program depending on certain variables or user input. When using an if statement you use a comparison operator. A list of these can be found here. Below is the simplest if statement:

Code :
<?php if(condition) { put code here to be executed when condition is true } ?>

To help you understand a little better there is a working example below:

Code :
<?php $variable = 10; if($variable == 10) { echo "The variable is equal to 10!"; } ?>
Output:
The variable is equal to 10!

That's a very simple example and an single if statement is not often useful. However an if...else statement is extremely useful as it can direct your script in certain directions, depending on user input or variables:

Code :
<?php if(condition) { put code here to be executed when condition is true } else { put code here to be executed when condition is false ?>
Code :
<?php $variable = 15; if($variable == 10) { echo "The variable is equal to 10!"; } else { echo "The variable does not equal 10!"; } ?>
Output:
The variable does not equal 10!

Often within a script you need to evaluate the same variable with multiple conditions/outcomes. This is where the if..elseif..else statement comes in:

Code :
<?php if(condition) { put code here to be executed when condition is true } elseif(condition) { put code here to be executed when condition is true } else { put code here to be executed when condition is false } ?>
Code :
<?php $variable = 11; if($variable < 10) { echo "The variable is less than 10"; } elseif($variable >= 10 { echo "The variable is greater than 10"; } else { echo "You did not enter a number!"; } ?>
Output:
The variable is greater than 10

However if we set our variable to "abc" this would be the result:

Code :
<?php $variable = abc; if($variable < 10) { echo "The variable is less than 10"; } elseif($variable >= 10 { echo "The variable is greater than 10"; } else { echo "You did not enter a number!"; } ?>
Output:
You did not enter a number!

This conclude the tutorial. In the next tutorial we will learn about switch statements. These are similar to if statements but offer great flexibility!



Login Required

To post comments you must sign in to your account below!

User :
Pass :

If you do not currently have an account click here to create one now!