Quantcast
Channel: Codehunterbd » PHP
Viewing all articles
Browse latest Browse all 10

Learn PHP-20 : The ?(ternary) Operator

$
0
0

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.


Filed under: PHP Tagged: PHP

Viewing all articles
Browse latest Browse all 10

Trending Articles