By odegard on
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
_
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.
Drupal coding standards are
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.
What's new and changing in PHP 8.4
I try to use the same
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.
Both are correct !!
PHP 7 allows for an even more readable variant
In PHP 7 we can use
$result = $somevariable ?? 'default';instead of the example above.Really?
$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!
Here's an interesting article
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.