Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ternary inside concatenation with no else? [duplicate]

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.

like image 362
Andrew Tibbetts Avatar asked Mar 01 '13 17:03

Andrew Tibbetts


3 Answers

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.';
like image 102
Antony Avatar answered Nov 11 '22 15:11

Antony


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));
like image 40
cwallenpoole Avatar answered Nov 11 '22 14:11

cwallenpoole


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

like image 1
Dashrath Avatar answered Nov 11 '22 15:11

Dashrath