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));
source share