Any PHP script that you write will have some sort of conditional statement in it because that is how the script will decide(for the lack of a better word) to what to execute next(like a “What now?!” for PHP).

There are different kinds of conditional statements available in PHP but in this part of this PHP Tutorial I will be discussing two of them that are being used the most in coding PHP scripts. These two methods are if…else and switch statement

Lets start with if statement:

if statement will check the result of a condition given to it and if the result is true then it will execute a command and if not it will execute another command here how it looks like in PHP:

if(condition){

Command to be executed if the condition is true

}else{

Command to be executed if the condition is false

}

so for example here are a few if statements:

$a=1;

$b=2;

if($a>$b){

echo “variable a is bigger than variable b”; // this will not be executed as 1>2 is false

}else{

echo “variable a is smaller or the same as variable b”;// this will be executed as 1>2 is false

}

Now you can make more than two if in one if statement using elseif like this:

$a=1;

$b=2;

if($a>$b){

echo “a is bigger than b”;

}elseif($a<$b){

echo “a is smaller than b”;

}else{

echo “a and b are the same”;

}

// the result is a is smaller than b

You can have as many elseif statements as you want in a single if statement also the above example is the same as the one below (just another way of writing it):

$a=1;

$b=2;

if($a>$b){

echo “a is bigger than b”;

}else{

if($a<$b){

echo “a is smaller than b”;

}else{

if($a==$b){

echo “a and b are the same”;

}

}

}

The condition part of the if statement can be anything that returns a true or false value it can be a function, a search query, variable or just like above a simple statement for more about the conditional operators look at the lesson about operators.

Now about switch statement :

Switch satement is basically the if…elseif…elseif…else staement that is much more efficient and faster, you will use it when you want to check a single variable with different values and then execute a specific command depend on which wa the correct value for that varaiable and here is how it looks like:

switch(variable){

case value1 :

commands to be executed ;

case value2 :

commands to be executed ;

case value3 :

commands to be executed ;

case calue n :

commands to be executed ;

}

here is an example:

$a= 2;

switch($a){

case 0:

echo “it’s zero<br />”;

break;

case 1:

echo “it’s one<br />”;

break;

case 2:

echo “it’s two<br />”;

break;

case 3:

echo “it’ three<br />”;

break;

}

this will produce “it’s two”

the “break;” will make sure that the switch statement will stop executing the rest of the switch statement after it has found the right answer. Here is the result of the same example without the breaks:

it’s zero

it’s one

it’s two

%d bloggers like this: