I want to check if 2 variables are the same and if so, echo a string. Is this possible within a concatenation? And to do it without creating a separate function?
e.g.
$var = 'here is the first part and '. ( $foo == $bar ) ? "the optional middle part" .' and the rest of the string.'
EDIT
Note, I'm looking to see if there is a way to do it without the : ''
. A "binary operator" if you will.
Don't try to shorten things up too much. You need that : ''
in order for things to work.
Use (condition) ? "show when true" : ""
to display an optional text depending on the condition. A ternary operator is named that way because it consists of 3 parts.
$var = 'here is the first part and '. (( $foo == $bar ) ? "the optional middle part" : "") .' and the rest of the string.';
If the question is "Can I do it without the colon and empty quotes?" The answer is no you cannot. You must have the closing :''
and it is best to use paren's 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're trying to do things inline. This basically boils down to the same process and does not use an unclosed ternary:
$var = 'here is the first part and ';
if( $foo == $bar ) $var .= "the optional middle part";
$var .= ' and the rest of the string.';
Whereas this is another way to accomplish the same goal without needing to worry about conditionals breaking the string:
$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 going to be needlessly clever, 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));
ternary operator syntex is as follows
(any condition)?"return this when condition return true":"return this when condition return false"
so in your string it should be like this
$var = 'here is the first part and '.( ( $foo == $bar ) ? "the optional middle part":"") .' and the rest of the string.'
which means your conditions is missing else past and operator precedence
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