In your example, the same makes use of a conditional operator whose condition is separated from the results by the character ?
and the results separated by the character :
.
What is a conditional operator "?:"
A conditional operator, as its name implies, is an operator operating on the basis of a condition.
It is part of the group of ternary operators because it takes three operands: a condition, a result for true, and a result for false.
In its essence, it is a simple way to summarize checks making the code more compact:
if ("condição") {
$bubu = "sim";
}
else {
$bubu = "não";
}
Turns into:
$bubu = "condição" ? "sim" : "não";
In this operator, the condition evaluation always returns a boleanus triggering the use of the first value in case TRUE
or second value in case FALSE
.
This operator is also known by the following names::
- IF conditional
- Shorthand IF
- Inline IF
- Ternary Operator (ternary operator)
Perks
- Makes logic programming simple
if
/ else
fastest
- Reduces the amount of code
- Makes code maintenance easier
Allows the use of logic inline avoiding breaking the code in multiple lines:
echo "Bem vindo, ".($loginAtivo?$primeiroNome:"Convidado").".";
Disadvantages
Except for the excess of its use, the conditional operator has no disadvantages. Its own creation started from the principle of simplifying small logical actions.
An example of its disadvantageous use where code maintenance becomes a nightmare:
// Devolve os dias em determinado mês
$dias = ($mes == 2 ? ($ano % 4 ? 28 : ($ano % 100 ? 29 : ($ano %400 ? 28 : 29))) : (($mes - 1) % 7 % 2 ? 30 : 31));
The example above is an incorrect use of this operator because reading the code is difficult, becoming more complete than regular if~else
.
Common mistakes
It is common to refer to this operator as operador ternário
, despite being a conditional operator of the group of ternary operators, because in the PHP language, it is the only one that exists. (?)
Another conditional Operator is the "?:" (or Ternary) Operator.
That translated:
Another conditional operator is the "?:" (ternary) operator.
The very PHP documentation for this operator leads us to make use of the name operador ternário
, that, as per reply by @Maniero:
The day you create another one - I doubt it will - will be confusing :)
PHP > 5.3
From PHP version 5.3, it is possible to further reduce the code, leaving out the middle part expr1 ?: expr3
:
$bubu = "sim" ?: "não";
Will return the first expression if it evaluates to TRUE
, otherwise returns the third expression.
The use in this form will no longer be so common, but to have been implemented, must come in handy at some point.
Possible duplicates: http://answall.com/questions/9962/comorsimplificar-o-seguinte-if-em-php/ or http://answall.com/questions/3647/quando-usar-condi%C3%A7%C3%A3o-tern%C3%A1ria ...
– Sergio