Do I need to include a false value in the triple PHP operator?

I need to add append data to a string, if the specific variable is true, if not, I don't need to add anything. I am currently doing:

$string = (condition()) ? 'something'.$string.'something' : $string; 

Is there any way to skip adding the false option in the ternary operator? It seems wasteful to say the string $ string = $ if the condition is false.

+6
source share
4 answers

You cannot miss it. You could re-write as a single-line if condition, though:

 if (condition()) $string = 'something'.$string.'something'; 
+3
source

Yes you need. Think of the ternary operator as a function. What would you expect from the behavior if you did something similar, but didn’t want to complete the task if condition() evaluates to false :

 $string = ternary(condition(), $yesValue, $noValue); 

You cannot undo the assignment in the $string variable if condition() is false.

+1
source

No, there is no way to skip this. If you want to skip the false bit, return to the if method:

 if (condition()) $string = 'something' . $string . 'something'; 

The ternary method is just a short if . If you can make the if as short without sacrificing readability (as in the example above), you should consider it.

But to be honest, I even formatted this to make it more readable:

 if (condition()) $string = 'something' . $string . 'something'; 

If you do not have enough monitor height, it will be easier to understand at a glance :-)

0
source

Not. This is the triple point. If you don't need a false value, why not just make a condition () return the required value?

Sort of:

 $string = condition($string); function condition($string){ if($string == 'whatever') { $string = 'something'.$string.'something'; } return $string; } 

I see that everyone else has already beaten me, so here are the docs for the triple:

http://php.net/manual/en/language.operators.comparison.php

-1
source

Source: https://habr.com/ru/post/909697/


All Articles