Is it possible to use the ternary operator in several conditions simultaneously?

3

Is it possible to use more than one condition at a time when using the ternary operator?

<?php 
    if($ativa == 0): echo "Médico(a) Desativado(a)"; 
    elseif($ativa == 1): echo "Médico(a) Ativo(a)";
    else: echo "Informação Indisponível"; endif;
?>

You can see that in the above condition there is a block of if / else / elseif . Is there a way to transform the above block using ternary operator?

    
asked by anonymous 21.08.2017 / 21:44

3 answers

6

Yes it is possible but DO not do ternary chaining in PHP because it makes the evaluations of the expression from the left different from most languages which in practice returns strange results (the middle one) perceive that the other answers made the thread but always with parentheses to set the priority.

Example of ternary that returns the result of the medium:

$ativo = 1;
$r =  $ativo == 0 ? 'Médico(a) Desativado(a)' : 
      $ativo == 1 ? 'Médico(a) Ativo(a)' :
      $ativo == 2 ? 'Outro' : 'else final';
echo $r;

The output: Outro

To fix this side effect , in PHP 5.3 the elvis operator ( ?: ) was introduced, it returns the first or last part of the expression. The simplest way I see is to do an array with status:

$descricao = array(0 => 'Médico(a) Desativado(a)', 1 => 'Médico(a) Ativo(a)', 2 =>'Outro');

$ativo = 5;
echo $descricao[$ativo] ?: 'Resultado padrão';

In PHP 7 you can use null coalescing ( ?? ):

echo $descricao[$ativo] ?? 'Resultado padrão';
    
21.08.2017 / 22:04
4

Do not do this, it's barely legible, but if you insist:

echo ($ativa == 0) ? "Médico(a) Desativado(a)" :
     ($ativa == 1) ? "Médico(a) Ativo(a)" :
     "Informação Indisponível";
    
21.08.2017 / 21:47
4

It's possible, but it's a good game to tell the truth:

echo ($ativa == 0) ? "Médico(a) Desativado(a)" : (($ativa == 1) ? "Médico(a) Ativo(a)" : "Informação Indisponível");

You actually add a ternary to else .

    
21.08.2017 / 21:47