简体   繁体   中英

Using a concatenation operator with a ternary conditional?

Is it possible to run two ternary conditionals, concatenating the results of the second to the first?

My conditionals read as follows:

$tr_class  = (!$pinned ?: "warning");
$tr_class .= ($read ?: " unread");

echo "<tr class='" . $tr_class . "'>";

If something is $pinned but !$read , I should get:

<tr class='warning unread'>

But I only get the ' unread' ? It seems like the second ternary conditional is overwriting the former, and not concatenating?

Is there away around this, without writing full if/else statements?

Yes is the short answer. If you could not concatenate the outputs of variables / invocation return values in PHP it would not have come very far as a language.

Your code works. I suspect the problem is with the values of $pinned and $read before it gets to your conditional statements.

If you neglect to put the 'is true' side of the ternary, it will take the value of the test which will usually be true or false, you should only leave this out if you want the 'is true' value to be the same as the conditional statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM