Decision making statements are essential in programming because they help us control the flow of execution in a program. The outcome of the condition which is specified in the decision-making statement will determine the lines of code which will be executed in the program.
Different actions can be taken depending on whether the condition evaluates to true or false. Because of this decision making statements are also known as conditional statements.
The following are the conditional statements available in PHP.
- if statement – This executes a particular set of statements only if the condition evaluates to true.
- if..else statement – executes a set of statements if a condition is true and another set of statements if the condition is false
- if.. elseif ... else statement – Multiple conditions are evaluated and different statement blocks get executed depending on which of the conditions is true.
- switch statement –selects one of the many blocks of code to be executed depending on the value of one condition.
IF Statement in PHP
The If.. condition statement allows us to execute a selected set of statements if a condition is true. If the condition is false the set of statements will be skipped during program execution.
Syntax :
Code:
Example :
Code:
IF…ELSE Statement in PHP
The If......Else statement is used if we want to execute a set of statements when a condition is true and execute another set of statements if a condition is false.
Syntax :
Code:
Example :
Code:
IF…ELSEIF…ELSE Statement in PHP
The IF…ELSEIF…ELSE statement is used because we want to execute one of the multiple sets of statements while testing more than one condition.
There could any number of conditions which could be evaluated and any number of sets of statements which could be executed because of the outcome of the conditions.
Syntax :
Code:
Example :
Code:
The output will be :
a is Bigger than b because $a>$b is true and $a==$b is false
Switch Statement in PHP
The switch statement is used to compare the same condition or expression with different values and execute the different set of statements because of its value match.
It is similar to a series of IF statements because it checks for the value of the same expression. However, it checks for the match of the exact value with the case labels. The switch statement is generally used because we can avoid long blocks of 'if..elseif..else' code.
Syntax :
Code:
Example :
The code evaluates the given expression and finds a label to match the resulting value. If the matching value of the label is found then the code associated with the matching label will be executed. The code in the default case will be executed when there is no match.
Code:
The output will be "Today is Monday because $d is 'Mon'"