I need to add append data to a string if a certain variable is true, if not, I don't need to append anything. Currently I'm doing:
$string = (condition()) ? 'something'.$string.'something' : $string;
Is there a way to skip adding the false option in a ternary operator? It seems wasteful to say $string = $string if the condition is false.
The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2); Condition: It is the expression to be evaluated and returns a boolean value.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.
The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
You can't skip it. You could re-write as a one line if
condition though:
if (condition()) $string = 'something'.$string.'something';
No, there's no way to skip it. If you want to skip the false bit, go back to the if
method:
if (condition()) $string = 'something' . $string . 'something';
The ternary method is just a short-hand if
statement anyway. If you can make the if
statement just as short without sacrificing readability (as in the example above), you should consider it.
But, to be honest, I'd even format that to make it more readable:
if (condition())
$string = 'something' . $string . 'something';
Unless you're desperately short of monitor height, that will be easier to understand at a glance :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With