php var structure not clear
what does this structure mean:
$var = isset($v开发者_开发百科ar_1) ? $var_1 : $var_2;
I came across it and of course with other values, not $va, $var_1 and $var_2.
thanks.
This is the ternary operator, and means the same as:
if (isset($var_1)) {
$var = $var_1;
}
else {
$var = $var_2;
}
The ternary operator provides a short-hand method of creating simple if/else statements.
It has some syntax errors, correctly:
$var = isset($var_1) ? $var_1 : $var_2;
This means:
if (isset($var_1))
{
$var = $var_1;
}
else
{
$var = $var_2;
}
That means:
if(isset($var_1))
$var = $var_1;
else
$var = $var_2;
It is short syntax for that.
just for your information from the php manual i copy pasted good things to know about ternary comparision operators
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:
Example #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
精彩评论