Skip to content

Instantly share code, notes, and snippets.

@tom--
Last active December 14, 2015 01:29
Show Gist options
  • Select an option

  • Save tom--/5006676 to your computer and use it in GitHub Desktop.

Select an option

Save tom--/5006676 to your computer and use it in GitHub Desktop.
Chaining the PHP ternary
<?php
// Some people object to this use of the ternary. I think it's fine so long as each
// condition-value pair fits nicely on one line. If so then the structure is highly
// expressive. The value $var takes is very obvious. The logic that
// this condition => that value, this condition => that value, etc. is plain to see.
$var =
condition1 ? 'value1' : (
condition2 ? 'value2' : (
condition3 ? 'value3' : (
'defaultValue'
)));
// The equivalent using a chain of ifs is less readable, to my mind. You have to scruitinize
// carefully to see that the entire block does nothing but set $var and that $var is
// unconditionally set after it executes, facts that are obvious from the first line of the
// ternary chain above. Moreover, all that repetitive if () { $var = } elseif () { $var = }
// visual clutter makes it hard to see the salient facts while in the ternary chain the
// condition-value pairs are neatly side-by-side.
if (condition1) {
$var = 'value1';
} elseif (condition2) {
$var = 'value2';
} elseif (condition3) {
$var = 'value3';
} else {
$var = 'defaultValue';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment