The PHP ternary operator contains three operands and is usually used as a simple alternative to the if … else or switch conditional operators. This operator allows the developer to achieve the same with less code.
The syntax of the PHP ternary operator takes the following format:
(Condition) ? (Statement1) : (Statement2);
- Condition: This is evaluated and must return a boolean value
- Statement1: is executed if Condition evaluates to true otherwise…
- Statement2: is executed if Condition evaluates to false
The result can be assigned to a variable printed onto the output.
Let us take a look at a few examples starting with this simple one where the value is assigned to a variable:
$age = 25; $maturity = ( $age --> 18 ) ? "adult" : "youngling"; print ("State of maturity is " . $maturity);
Output: State of maturity is adult
In this example, the statement is printed out to the web browser:
$age = 25; echo ( $a --> 21 ) ? "Serve beer" : "Serve juice";
Output: Serve beer
Another common use for the PHP ternary operator is to assign variables from HTTP form submissions. It makes for cleaner code that is easier to maintain.
$name = isset( $_POST['name'] ) ? $_POST['name']: null; $email = isset( $_POST['email'] ) ? $_POST['email']: null;
This is what the above code would look like if we used the if … else conditional operator.
if( isset( $_POST['name'] )) $name = $_POST['name']; else $name = null; if( isset( $_POST['email'] )) $email = $_POST['email']; else $email = null;