Learn PHP-20 : The ?(ternary) Operator

Posted: November 14, 2010 in PHP
Tags:

There is an operator in PHP that is very similar in functionality to the if statement called the ternary (?) conditional operator. It evaluates to check if the first subexpression is true, if it is it will return the value of the second subexpression, if the first subexpression is false it will return the value of the third subexpression.

Here is a code example using flavor variables and checking to see if the shop has our favorite flavor using ?:

<?php
// Let's say our choice is chocolate
$flavor_choice = "chocolate";
// And we do not know it yet but all they have is vanilla
$output = ($flavor_choice == "vanilla") ? "Yes, we have vanilla." : "Sorry we do not have $flavor_choice.";
// output the appropriate subexpression
echo "$output";
?>

The output is shown below :

Sorry we do not have chocolate.

Advertisements
Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s