I'm finding myself using the ternary operator control structure more and more. I usually do oneliners like this:

$result = isset($somvariable) ? $somevariable : 'default';

Recently I saw another format, one I like very very much increasing readability a lot:

$result = isset($somevariable)
  ? $somevariable
  : 'default';

One shouldn't go nuts with ternary operators but they are very useful in some cases.

There is no mention of ternary operators in the coding standards https://www.drupal.org/coding-standards

What do people use?

Comments

WorldFallz’s picture

I use the first form. While I agree the readability of the second is better, I'm usually using the ternary precisely because of its compact form. If I'm going to split it across lines anyway, then I might as well use if-then-else, lol.

ayesh’s picture

Drupal coding standards are based on Pear standards, which suggests the second. However, just as Worldfallz said, I too use the single-line format if it does not make the code look ugly or exceed the 80 char mark.

NormySan’s picture

I sometime use the first alternative if it's really short but i do prefer the second approach since it makes the core more readable and creates a nice little chunk that can have newlines before and after.

I prefer very readable code over trying to fit to fewer lines of code.

nitin.k’s picture


$result = isset($somvariable) ? $somevariable : 'default';


$result = isset($somevariable)
  ? $somevariable
  : 'default';


// Both follows proper spacing after operators ( = , ?, : ) that is what Drupal Coding standard says.

// Now second point is about new line - Code can be written using multiple lines but should have proper formatting.

// As per readability first one is superb.

gogowitsch’s picture

In PHP 7 we can use $result = $somevariable ?? 'default'; instead of the example above.

firfin’s picture

$new = isset($var)? $var: 'default'

is not really the same as

$new = $var?? 'default' 

is it?  In the first $new would be set to the value of $var is declared and is different than NULL , in the second the check is quite different from isset() ?

== EDIT

Sorry, you are absolutely right, https://www.php.net/manual/en/migration70.new-features.php#migration70.n...

Thanks for the tip!

jaypan’s picture

Here's an interesting article on various PHP operators https://www.designcise.com/web/tutorial/whats-the-difference-between-nul...

Contact me to contract me for D7 -> D10/11 migrations.