The ternary operator is a version of IF…ELSE
, which consists of grouping the condition statements in the same line.
traditional condition IF…ELSE
:
$sexo = 'M';
if($sexo == 'M'){
$mensagem = 'Olá senhor';
}else{
$mensagem = 'Olá senhora';
}
condition with ternary operator:
$sexo = 'M';
$mensagem = $sexo == 'M' ? 'Olá senhor' : 'Olá senhora' ;
The first parameter receives an expression, the second is the return if this expression is true, and the last one returns the value if the expression is wrong. So the variable $mensagem
gets the value Olá senhor
.
About, notice de undefined
is a simple warning that the variable was not initialized, ie the variable does not yet have a definition.