Why Not “Switch” from If/Else? Are you tired of writing if/elseif/elseif/…/else statements? You’re not alone. There is a more elegant way to write such large statements: the PHP switch statement. Let’s take a look at the anatomy of the switch statement. switch ( $arg ) { case “value_1”: expression if matched value_1 break; // terminate case “value_2”: expression if matched value_2 break; // terminate … default: execute if no cases matched } The switch statement accepts an argument. It has a series of “cases” that could potentially match the value of the argument. If it matches, the statements inside of that particular case are executed.
Month: January 2023
tired of if/else? How about ternary? The PHP Ternary Operator is a way to quickly express if/else statements. The ternary operator follows the following syntax: ( boolean expression ) ? if_true : if_false; If the boolean expression evaluates to true, the “if_true” result is displayed, otherwise the “if_false” result is displayed. Just as a quick recap, the normal if/else syntax looks like the following: <?php $expression = true; if ( $expression ) { // do statement if true } else { // do statement if false } ?> This gets redundant especially when you’re just echoing
Elseif: Between if and Else When you have more than 2 outcomes in your decision making, you’re going to need to use the PHP elseif statement. The elseif keyword goes in between the if and the else keywords. Your primary condition is handled by the if statement. If the condition is met inside of the if statement, there’s no point in testing any other conditions. The code that’s inside of the if statement body is executed and the remainder of the elseif/else statements are skipped. When the condition is not met, PHP will check the elseif statements next. If a condition matches, the code inside of that particular elseif statement body will execute and PHP will skip the remainder
What else is there? The PHP Else statements execute when the if statement’s condition evaluates to false. Remember, the expressions inside of the if statement can only execute when the conditional expression evaluates to true. The else keyword is appended right after the closing curly brace of the if statement. <?php $exercised = false; if ( $exercised ) { echo “You’re being healthy.”; } else { echo “Crickets”; ?> When the programmer chooses to omit the curly braces from the if statement because of a single line expression, the else keyword is appended immediately below the expression that’s
