PHP Ternary Operator

In PHP most of the oeprators are binary operators which combine two operands or expressions into a single but more complex expression. PHP has some unary and one ternary operators as well. Unary operators convert a single expression into a more complex expression and a ternary operator combines three expressions into a single expression.

A ternary operator is faster and cleaner way through which we can write simple if/else statements.

Syntax:

$variable = condition ? if true : if false

Portion to the left of the ? is a condition of testing. Portion between the ? and the : is the result/output if the condition is true. Portion after the : is the result/output if the condition is false.

Example

<?php
$cow = "white"; 
$x = ($cow = "white") ? "Wow! This cow is of my favourite colour." 
: "Uhh! This cow's colour is not favourite one.";
print $x;
?> 

This will produce following result:

Wow! This cow is of my favourite colour.


 
SHARE THIS IF YOU LIKE!
submit to reddit

SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.