Possible Duplicate:
the code “ : ” in php
I often see a lot of php code using ? and :, but I don't actually understand what it is for. Here an example:
$selected = ($key == $config['default_currency']) ? ' selected="selected"' : '';
Can someone clear me up, please? :)
It's the ternary operator. It's basically a if / else on one line.
For example, those lines :
if (!empty($_POST['value'])) {
$value = $_POST['value'];
} else {
$value = "";
}
can be shortened by this line :
$value = (!empty($_POST['value'])) ? $_POST['value'] : "";
It can make code easier to read if you don't abuse it.
(condition ? val1 : val2)
evaluates to val1
if condition
is true, or val2
if condition
is false.
Since PHP 5.3, you may also see an even more obscure form that leaves out val1
:
(val0 ?: val2)
evaluates to val0
if val0
evaluates to a non-false value, or val2
otherwise. Yikes!
See http://php.net/manual/en/language.operators.comparison.php
It's shorthand for an if statement
You can turn that statement into this:
if ($key == $config['default_currency']) {
$selected = ' selected="selected"';
} else {
$selected = '';
}
It's the ternary conditional operator, just like in C.
Your code is equivalent to:
if ($key == $config['default_currency'])
{
$selected = ' selected="selected"';
}
else
{
$selected = '';
}
In pseudocode,
variable = (condition) ? statement1 : statement2
maps to
if (condition is true)
then
variable = statement1
else
variable = statement2
end if
精彩评论