Tuesday, January 27, 2009

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.

1 comment:

shopping cart said...

It is such a useful tip about the ternary used in PHP and it provide simple alternative way for the programing.