Showing posts with label if else. Show all posts
Showing posts with label if else. Show all posts

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.