Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP ternary operator

The ternary operator is another conditional operator, but it is worth putting it separately. It performs a similar action to if else.

(expr1) ? (expr2) : (expr3)

Note that all are expressions, both expr1, expr2, and expr3. With the ternary operator, if expression 1 is true, expression 2 will be evaluated; otherwise, expression 3 will be evaluated.

The best way to understand the operator is through examples. For example, in the following code, I check if the message arrives:

check if the message arrives
echo $message;


A question we may ask ourselves about this operator is whether nesting can be done inside it, in other words, if we can put a ternary operator inside another one. The answer is yes, it is an expression, and therefore, we can put it inside any place where an expression is expected.

Nesting example
$stock = 0;
$b=("no-stock")?($stock==0)?"no stock":"not-defined":"not-price";
echo $b;
no stock
Note: Although nesting may seem very useful, it is recommended not to use it because the idea of what the code does in each of them is lost.

Elvis operator

You may also see this operator as follows, the name of the Elvis operator comes from the fact that the operator looks like Elvis Presley’s hair:

(expr1) ?: (expr3)

This expression is equivalent to writing (expr1) ? (expr1) : (expr3).

Elvis operator example
echo $b;
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category