Keep in mind that it's an OPERATOR, which means that it requires OPERANDS and results in a value. So when you think about it, it's not a shorthand method of writing expressions, it's just a kind of expression you can write.
Saying that ?: is shorthand is like saying ++ is shorthand for "+1" -- you can think of it that way if you want, but that's not TECHNICALLY accurate.
Because these are operators that form their own expressions, you can include them within other expressions.
For example: 4 + 3 is an expression, the operator is +, the operands are 4 and 3, the result is 7. You can use that expression within other expressions: 5 * (4 + 3). Same thing goes with the ternary operator. Also, the $first of Rich's quote is really a placeholder for a BOOLEAN expression, you're not limited to using just a variable -- you can call functions that return boolean values, or create expressions of your own.
Here goes with something a little more complex:
$submitted_form = isset($_POST['username'])? (isset($_POST['password'])? TRUE : FALSE) : FALSE;
See, if 'username' was submitted, then we evaluate the second ternary expression. That one
evaluates to true (don't say "returns true" because it's NOT a function!!) if 'password' was submitted and false if it wasn't. Otherwise (that is, if 'username' was not submitted), the expression evaluates to false.
That translates to this long-winded code:
if (isset($_POST['username']))
{
if (isset($_POST['password']))
{
$submitted_form = true;
}
else
{
$submitted_form = false;
}
}
else
{
$submitted_form = false;
}
One thing to notice about this: $submitted_form is ALWAYS assigned a value. If you've got if/else chains or other conditional code where a variable is ALWAYS assigned something, chances are you can clean things up by assignign the result of a ternary operator expression.
Of course, the above can be rewriten without loss of functionality as:
if (isset($_POST['username']) && isset($_POST['password))
{
$submitted_form = true;
}
else
{
$submitted_form = false;
}
...but that is a translation of THIS ternary expression:
$submitted_form = (isset($_POST['username']) && isset($_POST['password']))? true : false;
This example is admittedly lame, because the value of the expression when it's evaluated IS EXACTLY the value of the conditional part. It's like:
$foo = true ? true : false; or $foo = false ? true : false;
One can cut out the ternary operation completely:
$foo = true; or $foo = false;
Relating it to our example:
$submitted_form = isset($_POST['username']) && isset($_POST['password']);
Okay, rambling over.
Take care,
Nik
http://www.bigaction.org/