PHP triple inside concatenation no more?

I want to check if 2 variables are the same, and if so, the echo line. Is this possible in concatenation? And do it without creating a separate function?

eg.

$var = 'here is the first part and '. ( $foo == $bar ) ? "the optional middle part" .' and the rest of the string.'

EDIT

Notice I am looking to see if there is a way to do this without : '' "Binary operator" if you want.

+4
source share
3 answers

Do not try to shorten things too much. For this you will need : '' .

Use (condition) ? "show when true" : "" (condition) ? "show when true" : "" to display optional text depending on the condition. The ternary operator is so named because it consists of three parts.

 $var = 'here is the first part and '. (( $foo == $bar ) ? "the optional middle part" : "") .' and the rest of the string.'; 
+10
source

If the question is: β€œCan I do this without a colon and empty quotation marks?” The answer is no, you cannot. You should have a closure :'' , and it is best to use a pattern to clarify your desires.

 $var = 'here is the first part and '. (( $foo == $bar ) ? "the optional middle part":'') . ' and the rest of the string.' 

I think the biggest problem here is that you are trying to do something inline. This basically boils down to the same process and does not use a closed triple:

 $var = 'here is the first part and '; if( $foo == $bar ) $var .= "the optional middle part"; $var .= ' and the rest of the string.'; 

While this is another way to achieve the same goal without worrying about conditional line breaks:

 $middle = ''; if( $foo == $bar ) $middle = ' the optional middle part and'; $var = sprintf('here is the first part and%s the rest of the string.',$middle); 

Now, if you are uselessly smart, I suppose you could do this instead:

 $arr = array('here is the first part and', '', // array filter will remove this part 'here is the end'); // TRUE evaluates to the key 1. $arr[$foo == $bar] = 'here is the middle and'; $var = implode(' ', array_filter($arr)); 
+1
source

the ternary syntex operator is as follows

 (any condition)?"return this when condition return true":"return this when condition return false" 

so in your line it should be like

 $var = 'here is the first part and '.( ( $foo == $bar ) ? "the optional middle part":"") .' and the rest of the string.' 

which means that in your conditions there is no other past and operator’s priority

+1
source

All Articles