Is it possible to use the ternary operator under several conditions at the same time?

Asked

Viewed 10,900 times

5

It is 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. There would be a way to transform the above block using ternary operator?

  • 1

    Doesn’t chain ternaries mainly in php.

  • I’ll take the advice then. It was more of a question as to whether and how @rray

4 answers

10

Yes it is possible but DO NOT CHAIN TERNARIES 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) realize that the other answers made the chaining but always with parentheses to define the priority.

Ternary example that returns the middle result:

$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 way out : Outro

To fix this side Effect, in PHP 5.3 the operator was introduced Elves (?:), it returns the first or last part of the expression. The simplest way I see is to make 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';

5

It’s even possible, but it’s pretty tricky to tell the truth:

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

In fact you add a ternary to the Else.

5

Don’t do this, it’s barely readable, but if you insist:

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

I put in the Github for future reference.

  • It really gets very unreadable

  • And I left reasonable breaking line, in the same line becomes terrible. No te the original code and this does not even seem to wish.

0

Yes! I did it once and it worked. Every time we put a new condition we have to put the variable assignment again. I’ve tried a lot to do without assigning variable, but it doesn’t work. I even made a test assigning any variable even without using it and it worked, but I undone this "gambiarra" and then again assigning a variable correctly.

Solution:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.