Dreevoo.com | Online Learning and Knowledge Sharing
 
Home | Programs | Programming languages | PHP & MySQL | PHP Conditional IF and SWITCH Statements
Guest
Click to view your profile
Topics
Programs
Languages
Recipes
Home
Shortcuts
 
 

PHP Conditional IF and SWITCH Statements

Conditional statements are used to perform different actions based on different conditions and are used in almost every PHP application.

 
  Author: podtalje | Version: php.net | 7th April 2013 |  
 
 
1.
 

In most of the cases when conditional checking is needed, we will use IF condition

The following example represents the if statement in its most basic form:

<?php
$t=20;
if ($t==20)
{
   echo 'Value of variable $t is 20';
}
?>


In the example we check if the value of variable $t equals 20 and because the condition is true, text will be printed out.

Please also be aware that we are using == operator for checking condition, because operator = is reserved for assigning the value to variable.

We can of course also use other common conditional operators >, <, >=, <= or != (not equal).

 
 
2.
 

IF .. ELSE ..

We can also add else statement which will be executed when the condition would be false.

<?php
$t=20;
if ($t==20)
{
   echo 'Value of variable $t is 20';
}
else
{
   echo 'Condition is false';
}
?>


 
 
3.
 

IF .. ELSE IF .. ELSE IF .. ELSE ...

We can also verify several conditions in a row:

<?php
$t=20;
if ($t==20)
{
   echo 'Value of variable $t is 20';
}
else if ($t==21)
{
   echo 'Value of variable $t is 21';
}
else if ($t==22)
{
   echo 'Value of variable $t is 22';
}
else
{
   echo 'Condition is false';
}
?>

 
 
4.
 

SWITCH statement

If there are many conditions to be checked, we can also use a little shorter form by using switch statement.

<?php
$t=20;
switch ($t)
{
  case 20:
    echo 'Value of variable $t is 20';
    break;    
  case 21:
    echo 'Value of variable $t is 21';
    break;    
  case 22:
    echo 'Value of variable $t is 22';
    break;    
  default:
    echo 'Condition is false';
}
?>


In the example above we have also used break command which will prevent checking conditions that follow and will exit immediately.

 
 
5.
 

As you can see IF conditions are not very complicated. Because they are used in almost every PHP script, you should really know how to use them.

The best way to learn this is to try the example above yourselves.

Try changing the value of variable $t and check the output of your script.

And of course if you have any questions, just write on forum and we will try to give you the best answer.

 
 
 
   
  Please login to post a comment
   
 
 
online learning made for people
Dreevoo.com | CONTRIBUTE | FORUM | INFO