PHP If-Else, Switch Case and shorthand Ternary operator example

Sometimes we need to perform different actions based on the decision, PHP provides several conditional statements that can be used for this.

  1. If statement – its used when you need to execute the piece of code only when the condition is true.
  2. If-Else statement – its used to execute a piece of code when the condition is true or another piece of code when condition is false.
  3. If-Else-If Statement – its used when there are multiple code that can be executed based on the condition, as soon as one of the condition is true and its code block is executed, control comes out of the statement.
  4. Switch statement – Its same as if-else-if statement but it make code cleaner.
  5. Ternary Operator – Ternary operator provides a shorthand way to write all the above conditional statements. If the condition is not very complex, its better to use ternary operator to reduce the code size but for more complex conditions, it can become confusing. The syntax is (Condition) ? <Condition=True>:<Condition=False>

Here is an example PHP script showing usage of all the conditional statement and using ternary operator to implement the same logic in very small size of code.

Output of the above PHP script is:

Further reading: PHP Operators

By admin

Leave a Reply

%d bloggers like this: