phpconditional-operator

Converting if/else to ternary operator


I'm just getting to grips with ternary operators in PHP and am having trouble converting the following:

<? if( $link['file'] ): ?>
  <?=$link['file'] ?>
<? else: ?>
  <?=$link['link'] ?>
<? endif ?>

My attempt so far, that generates an error:

<? if( $link['file'] ) ? $link['file'] : $link['link']; ?>

Any pointers how to get this conversion working, it must be close?


Solution

  • With shorthand form ?:

    <?= $link['file'] ?: $link['link'] ?>
    

    Full form:

    <?= $link['file'] ? $link['file'] : $link['link'] ?>