Search code examples
phpechoconditional-operator

How to write a ternary in PHP when you need an echo for only one condition?


I have some code

<?php (($f[2] != '') ? $f[2] : implodeList($l[3])); ?>

And the first condition: $f[2] requires an echo so the following works with that condition is met:

<?php echo (($f[2] != '') ? $f[2] : implodeList($l[3])); ?>

How the function for the second condition outputs an echo statement and can't change so only the first version of the code works if that condition is met.

I'm I stuck foregoing a ternary in this instance? I could rewrite with a standard IF. Secondary question, can you explain why they didn't make it possible to put the echo inside the ternary itself? Like:

<?php (($f[2] != '') ? echo $f[2] : implodeList($l[3])); ?>

In the past I've found that could've been useful.


Solution

  • You can just use print instead of echo, because unlike echo, print behaves like a function which makes it valid to use in a ternary expression like this:

    <?php $f[2] != '' ? print($f[2]) : implodeList($l[3]); ?>
    

    Demo on 3v4l.org