How to Use The PHP Ternary Operator With Examples

PHP Ternary Operator

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 of 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:

State of maturity is adult

This example the statement is printed out to the web browser:

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.

This is what the above code would look like if we used the if … else conditional operator.