View Full Version : Ternary conditionals

04-29-2008, 01:40 PM
Bit bored so I thought I would show you an example of how to reduce/imporve your coding by using the ternary operator:

an example if else statement

if ($age < 15 ) {
echo "This film is for 15's and over";
} else {
echo "Enjoy your film";

achieving the same with the ternary operator:

echo ($age < 15 ) ? "This film is for 15's and over" : "Enjoy your film";

you can also assign the value to a variable to use later in your script

$some_var = ($age < 15 ) ? "This film is for 15's and over" : "Enjoy your film";

04-29-2008, 04:45 PM
They are more expensive than if/else but unless you have thousands on one page or have a very high traffic site where every millisecond is crucial it doesn't really matter.

I also nest them like:

$some_var = ($age < 15 ) ? "This film is for 15's and over" : (isset($a_var)?'a var is set':'a var isn\'t set'); I probably wouldn't nest too deeply though as it gets harder to read and debug.

04-29-2008, 10:15 PM
Cheers for expanding on this Pete