Using the Ternary Operator
PHP/MySQL
Last Updated: 2007-01-27 16:17:57
Last Updated: 2007-01-27 16:17:57
STEP 1: The ? or Ternary Operator
The ternary operator is similar to a really simple if statement. It tests if a condition is true or false and returns a result based on the findings.
The syntax looks like so:
<?
$mood = "happy";
$text = ( $mood=="happy" )?"Hooray, I'm in a good mood":"Not happy but $mood";
print "$text";
?>
If the test expression returns true the first expression after the ternary object is returned. If false the second is returned.
This script would print, "Horray, I'm in a good mood", because the expression $mood=="happy" returned true.
The syntax looks like so:
<?
$mood = "happy";
$text = ( $mood=="happy" )?"Hooray, I'm in a good mood":"Not happy but $mood";
print "$text";
?>
If the test expression returns true the first expression after the ternary object is returned. If false the second is returned.
This script would print, "Horray, I'm in a good mood", because the expression $mood=="happy" returned true.
This is the JoeLucky39 tutorial section. Feel free to use whatever information you find here on your own site(s). Know that not all tutorials are ideal for all sites, so feel free to modify the information contained in this tutorail section as best suits your web site.
At JoeLucky39 you can find tutorials on Comic Art, PHP/MySQL, and more are added all the time. So, visit often and feel free to contact Joe if you think that his tutorials need to be changed or updated.
Joe believes in the open source movement and is happy to share his knowledge with anyone who asks. All Joe asks is, if you use Joe's open source tutorials, you share your knowledge as well.
Thank you and I hope you find what you are looking for. If not feel free to contact me and ask.
