Use several ternary conditions in php

Asked

Viewed 398 times

-1

How to use several ternary condition in the same line?

Example:

echo ($estado == 'SP' ? 'São Paulo' : ($estado == 'RJ' ? 'Rio de Janeiro') : ($estado == 'PR' ? 'Paraná') : 'teste');

That way you’re making a mistake!

1 answer

0


You can even use this but, as you can see, the readability of the code is horrible.

"Identando" the condition can be seen where the error is (in the control of the parentheses):

echo
($estado == 'SP' ? 
   'São Paulo' : 
   ($estado == 'RJ' ? 
      'Rio de Janeiro') : 
      ($estado == 'PR' ? 'Paraná') : 
          'teste');

The correct setup would look like this:

echo
($estado == 'SP' ? 
   'São Paulo' : 
   ($estado == 'RJ' ? 
      'Rio de Janeiro' : 
      ($estado == 'PR' ?
          'Paraná' : 
          'teste')
    )
 );

//em uma linha só:
echo ($estado == 'SP' ? 'São Paulo' : ($estado == 'RJ' ? 'Rio de Janeiro' : ($estado == 'PR' ? 'Paraná' : 'teste')));

remembering: in cases with more than one validation, it is more interesting to use if or switch.

  • 2

    It worked out! Thank you very much!

Browser other questions tagged

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