Sunday, December 22, 2013

PHP: if, elseif, and switch case statement

Hi friends today we will see if statements, elseif statement and switch case in PHP. First of all we will have a look at if statement,
*If…else statement:
It’s most basic use is for making decisions on the basis of conditions. Let’s take an example to understand if statement.
Example 1:

Output:

[fig 01: Code for if..else statement]
As we can see in (fig 01), that “==” has been used to compare a variable with a string or value. Else statement get executed only when condition given in if statement becomes false. 
*Elseif statement:
Elseif statement can be used to check multiple conditions to be true. One thing that we have to be aware of is that elseif statement must be used only after we have first declared if statement.
Let’s see the example for this statement too.

Output:

[fig 02: Code for elseif statement]
As shown in (fig 02), after if statement fails elseif statement gets executed.
*Switch case:
The fast and compact alternative to if…elseif statement for checking multiple conditions is switch case statement.
Let us see it by example:

Output:

[fig 03: Code for Switch case statement]
Here in (fig 03), we can see that there are multiple cases each case is unique and when the variable declared match with current case then that case code is executed. Just like if statement where if the given condition does not satisfy then else code get executed similarly in switch case if all the given cases fails then last case which is default gets executed. We must notice the break keyword in each case that is given so that when the execution of particular case gets finished then execution comes out of whole switch case and next line after switch case gets executed.

*NOTE:
If you have any doubts or queries please refer previous blogs of mine and comment below too so that we both can learn from our mistakes.