View Full Version : Usage of '?' & ':' in PHP....

03-03-2008, 10:19 PM
Hey guys.... kind of a dumb question, been coding PHP for over 3 years now & for some reason never come across finding out what these mean....

See the below code..

$bla = isset($_POST['blah']) ? $_POST['blah'] : false;

echo '<select name="blah">';

echo '<option value="opt_1" '. $bla == 'opt_1' ? 'selected="selected"' : '' .'>1</option>';
echo '<option value="opt_2" '. $bla == 'opt_2' ? 'selected="selected"' : '' .'>2</option>';
echo '<option value="opt_3" '. $bla == 'opt_3' ? 'selected="selected"' : '' .'>3</option>';

echo '</select>';

What exactly is the use of the '?' & ':' in the above code?

Thanks guys! :thumbsup:

03-03-2008, 10:59 PM
It's called the ternary operator (http://php.net/language.operators.comparison#language.operators.comparison.ternary). It's basically a shorthand if/else.

03-04-2008, 01:24 AM
Great..... thanks for that! :)

03-04-2008, 03:13 AM
I LOVE ternary operators :P Makes for much cleaner code when you don't really need to do anything but switch a variable around. It kind of amazes me that you've never seen it before. Maybe just haven't looked at any of my code I guess :P If there where a thing such as a "ternary operator whore" I'd be one ;)