The Ternary Operator – Working same as If-Else
We know, in programming there are three operators named Unary Operator , Binary Operator and Ternary Operator.
Operator's name itself says that if it is a Unary Operator(e.g. Increment – Decrement operators) than it will take only one operand, If it is Binary operator(e.g. Relational operators) than it will take two operands and if it is Ternary operator than it will take three operands.
As discussed above, Ternary operator takes three operands – a condition, a result for true, and a result for false. It works similar to IF statement. Ternary operator will compact the 4-5 lines of code(IF statement) in to single line. This makes a difference when you will work with big application and writing thousand lines of code.
Look at below links for solutions.
Look at the below example of IF condition code in PHP.
if($a>$b)
{
echo "$a is greater than $b";
}
else
{
echo "$b is greater than $a";
}
Now same thing can also be done by Ternary operator.
echo $a>$b ? "$a is greater than $b" : "$b is greater than $a" ;
To know more about programming,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.






I am
about 2 years ago
Agree that Ternary operator is very much useful for making your program code small as it will reduce the number of lines.
May be it will make some difference in speed of execution.
Will it be a faster execution ??
about 2 years ago
Agree that Ternary operator is very much useful for making your program code small as it will reduce the number of lines.
May be it will make some difference in speed of execution.
Will it be a faster execution ??
about 1 year ago
how would you use the ternary operator to create a statement equivilent to the following:
;
;
if(a == b) {
header('location:http://www.google.com'
}else{
header('location:http://www.yahoo.com'
}
about 1 year ago
how would you use the ternary operator to create a statement equivilent to the following:
;
;
if(a == b) {
header('location:http://www.google.com'
}else{
header('location:http://www.yahoo.com'
}