Monday 26 January 2009
Facebook StumbleUpon Twitter Google+ Pin It

PHP Ternary Operator

Consider the following snippet of code:

if (condition){
 variable = value1;
}else{
 variable = value2;
}

Instead of doing that way, we can just simply do it like this:

variable = condition ? value1 : value2;

Another variation of using the ternary operator would be from:

if (condition){
 echo "something1";
}else{
 echo "something2";
}

And it can be expressed like:

echo condition ? "something1": "something2";

You can also nest the condition:

variable = cond0 ? (cond1 ? value1.1 : value1.2) : (cond2 ? value2.1 : value2.2);

Just use your imagination on how to use this form.



Parthiv Patel
Bhaishri Info Solution
Sr. PHP Developer
Limdi Chowk, AT PO. Nar, Di. Anand
Nar, Gujarat
388150
India
pparthiv2412@gmail.com
7383343029
DOB: 12/24/1986

No comments: