Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate + Ternary

Tags:

php

In PHP, is there a way to concatenate two strings using a ternary conditional?

<?= 'something' . (true) ? 'else' : 'not'; ?>

When I try that, all I get is else rather than the desired something else.

like image 214
cantera Avatar asked Sep 06 '25 03:09

cantera


2 Answers

Just put brackets around the entire ternary operator like this:

<?= 'something' . ((true) ? ' else' : ' not'); ?>

Why do you have to do that?

The answer is: operator precedence

See the manual for more information: http://php.net/manual/en/language.operators.precedence.php

like image 156
Rizier123 Avatar answered Sep 07 '25 18:09

Rizier123


Yes, you need to put your ternary in brackets though. Try this:

<?php echo 'something '.((true) ? 'else' : 'not'); ?>
like image 39
Styphon Avatar answered Sep 07 '25 19:09

Styphon