PHP Conditional Statements are found in every programming language, these allows the program to decide a particular path of execution based on a comparative conditions.
In Conditional statement, a condition is tested and then according to the result of the testing, i.e. either
FALSE, an action is performed.
|if statement||Executes a block of code if the given condition is true.|
|if-else statement||Executes a block of code if a condition is true or another block of code if that condition is false.|
|if elseif else statement||Used to test more than one condition with different blocks of code.|
|switch statement||Alternative for If-elseif statement.|
The PHP If statement is used to test a condition and then based on the results, if the condition is
TRUE then a particular block of code is executed
otherwise if the result is
FALSE then the block of code is ignored and nothing happens. You can test more than one condition by using
'OR' operators. Let's see an example to understand it properly, also look at the syntax and write it down:
As you can see in the example above, the condition evaluates to be TRUE and then a line got printed. But when the condition evaluates to false, then the block of code got ignored and nothing happened.
The If statement only performs an action when the given condition is TRUE, but what if we also want to give an alternative block of code in case of a FALSE evaluation.
For this we need
if-else statement, It allows the programmer to define actions for both scenarios.
The if-else statement provide two blocks of code, one under
'if' and the other under
If the condition evaluates to TRUE then the 'if' part will get executed otherwise the 'else' part will be executed.
Till now we were performing actions based on a given condition, but what if we want to test multiple conditions and want to define a block of code for each condition? We will use the if-elseIf Statement. We use this when we have multiple conditions of TRUE cases.
It sounds a bit complex but it is not, once you get familiar with the syntax, you will understand it quickly:
In this scenario all the condition will be checked one by one and if any one of them evaluates to TRUE then the block of code for that condition will be executed and all other blocks will be ignored but if all the conditions evaluates to FALSE then the 'else' statement's block will be executed. Look at the example below and try to understand it step by step.
The Trenary operators are a form of Shorthand Technique for the If-else statement.
It uses a question mark (
?) and a colon (
:) with three operands: a condition which will be evaluated, an action for TRUE and an action for FALSE. Look at the syntax and things will get cleared