-1

I have found myself in the ' and " hell. Can't figure out why this is not working. Would appreciate some fresh experienced over it. Thanks

foreach($channels as $channel)
{
    echo '<option value="'.$channel['id'].'" '.($channel['id'] == 2) ? 'selected' : ''.'>'.$channel['name'].'</option>';
}
CBroe
  • 91,630
  • 14
  • 92
  • 150
G. Malla
  • 1
  • 1
  • 1
    Do yourself a favor, and use this syntax: https://www.php.net/manual/en/language.basic-syntax.phpmode.php – CBroe Jul 15 '21 at 11:13
  • 1
    Try putting some parenthesis around `($channel['id'] == 2) ? 'selected' : ''` – Michel Jul 15 '21 at 11:15
  • Also you don't need the `)` you have immediately after `== 2)`. So basically move that closing `)` from its current position to after the `''` as Michel suggests. `($channel['id'] == 2 ? 'selected' : '')` – duncan Jul 15 '21 at 11:19
  • Move the ) to the end? OMG! yes that works. Thanks Michel and duncan – G. Malla Jul 15 '21 at 12:13

1 Answers1

0

This is where PHP's alternative syntax for control structures really shines as a templating syntax

foreach ($channels as $channel): ?>
<option
  value="<?= htmlspecialchars($channel['id']) ?>"
  <?= $channel['id'] == 2 ? 'selected' : '' ?>
>
  <?= htmlspecialchars($channel['name']) ?>
</option>
<?php endforeach ?>
Phil
  • 157,677
  • 23
  • 242
  • 245