Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

How to use ternary operator?

This is my code, first one if statement is working fine but the second when i convert it to ternary, it is not working

<option value="en"<?php if(in_array('en', $languages)) {echo ' selected';} ?>>English</option>
<option value="fr"<?php in_array('fr', $languages) ? ' selected' : '' ?>>French</option>

I don't want to use else statement in ternary. I am running a PHP 7.

1 Answer

Andrew McCormick
Andrew McCormick
17,730 Points

In your ternary operator you need to echo something out.

<option value="fr"<?php echo in_array('fr', $languages) ? ' selected' : '' ?>>French</option>

As a side note, my go to resource everyti me I forget how to setup ternary statement (which is every time I go to use it, lol) is https://davidwalsh.name/php-shorthand-if-else-ternary-operators