- If statement – its used when you need to execute the piece of code only when the condition is true.
- 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.
- 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.
- Switch statement – Its same as if-else-if statement but it make code cleaner.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php $a=15; $str="David"; $str1="Pankaj"; $color="Red"; //if condition example if($a==15){ echo "value of a is 15"; echo "<br>"; } //if-else condition example if($str1 == "Pankaj"){ echo "Hi Pankaj"; echo "<br>"; }else { echo "Hi There!"; echo "<br>"; } //if-else-if example if($str == "Pankaj"){ echo "Hi Pankaj"; echo "<br>"; }else if($str == "David"){ echo "Hi David"; echo "<br>"; } else{ echo "Hi There!"; echo "<br>"; } //switch statement example switch ($color){ case "Red": echo "Red Color"; break; //for breaking switch condition case "Green": echo "Green Color"; break; default: echo "Neither Red or Green Color"; } echo "<br>"; //PHP ternary operator example // implementing the above if example with ternary operator echo ($a == 15) ? "value of a is 15"."<br>":""; // implementing the above if-else example with ternary operator echo ($str1 == "Pankaj") ? "Hi Pankaj"."<br>" : "Hi There!"."<br>"; //implementing above if-else-if example with ternary operator echo ($str == "Pankaj") ? "Hi Pankaj"."<br>" : (($str == "David") ? "Hi David"."<br>" : "Hi David"."<br>"); //implementing switch statement with ternary operator echo ($color == "Red") ? "Red Color" : (($color == "Green") ? "Green Color" : "Neither Red or Green Color"); ?> |
Output of the above PHP script is:
1 2 3 4 5 6 7 8 9 10 |
value of a is 15 Hi Pankaj Hi David Red Color value of a is 15 Hi Pankaj Hi David Red Color |
Further reading: PHP Operators