Decision making in PHP
Like most programming languages, PHP also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time. This means, we can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions. Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. We need to determine which action to take and which statements to execute if outcome is TRUE or FALSE.
If then else
PHP, like Python, has an if statement for decision making. It consists of a boolean expression that if evaluated to true, will execute a code block. The if statement can also have an else clause which will execute if the boolean expression evaluates to false. The if statement can be daisy chained to multiple if statements.
if(condition1){ // Code to be executed if condition1 is true } elseif(condition2){ // Code to be executed if the condition1 is false and condition2 is true } else{ // Code to be executed if both condition1 and condition2 are false }
The Ternary Operator
The ternary operator provides a shorthand way of writing the if...else statements. The ternary operator is represented by the ? symbol and it takes three operands, a condition to check, a result for true, and a result for false. Using the ternary operator the same code could be written in a more compact way. Code written using the ternary operator can be hard to read. However, it provides a great way to write compact if-else statements.
Lines 1 - 8 can be re-written using the ternary operator as seen in line 10.
Switch statements
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match. The major difference is that the test for the variable happens only once.