Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to include a false value in a ternary operator PHP?

Tags:

php

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.

like image 222
Ayub Avatar asked Mar 01 '12 01:03

Ayub


People also ask

What's the correct syntax for a ternary operator in PHP?

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.

How do you condition a ternary operator?

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.

Why we should not use ternary operator?

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.

How many arguments are needed in ternary 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.


2 Answers

You can't skip it. You could re-write as a one line if condition though:

if (condition()) $string = 'something'.$string.'something';
like image 52
gregheo Avatar answered Sep 17 '22 23:09

gregheo


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 :-)

like image 38
paxdiablo Avatar answered Sep 19 '22 23:09

paxdiablo