I was writing some code today and decided to use nested ternary operators to get a value that I was going to use.
My application logic was as follows.
I needed to set my $current_value to be the value of $_GET['zip'] if it exists, if it doesn't I wanted to get the value from $_SESSION['search']['zip'] if it exists, if that doesn't then I'll set $current_value = ''.
The typical fashion of the code would be:
<?php if(isset($_GET['zip'])) { $current_val = $_GET['zip']; } elseif(isset($_SESSION['search']['zip'])) { $current_val = $_SESSION['search']['zip']; } else { $current_val = ''; } ?>
What is wrong with this code? The answer really is 'nothing'. It's easy to read, it does the job, and it's very easy for anybody (who develops) to understand it.
Now what it would look like using a nested ternary operator.
<?php $current_val = (isset($_GET['zip'])) ? $_GET['zip'] : (isset($_SESSION['search']['zip']) ? $_SESSION['search']['zip'] : ''); ?>
Ternary Operator Pros: The ternary operator method has less code, if you're familiar with ternary operators, you indent properly, and you keep your operation simple, it's very easy to understand.
Ternary Operator Cons: Remember the first time you saw a ternary operator? The syntax is like nothing you've ever seen and you don't even have a function name to look up to see what the hell you are looking at. Also ternary operators can get very ugly, very quickly and like SQL it helps to indent the operation so you can easily read it. Also you can't really debug your ternary operation without splitting apart what you've written and that would be another reason to stay away from them.
So my advice would be:
Use ternary operators sparingly, keep them simple, and don't nest them. You may feel that you're being very clever, however chances are you're decreasing readability of your code, and making it harder for an inexperienced developer to understand your code. You should understand how to use them though.

Leave a Comment