Possible Duplicate:
What are the PHP operators "?" and ":" called and what do they do?
Reference - What does this symbol mean in PHP?
I know what isset
means in PHP. But I have seen syntax like isset($x) ? $y : $z
. What does it mean?
Possible Duplicate:
What are the PHP operators "?" and ":" called and what do they do?
Reference - What does this symbol mean in PHP?
I know what isset
means in PHP. But I have seen syntax like isset($x) ? $y : $z
. What does it mean?
That is a Ternary Operator, also called the "conditional expression operator" (thanks Oli Charlesworth). Your code reads like:
if $x is set, use $y, if not use $z
In PHP, and many other languages, you can assign a value based on a condition in a 1 line statement.
$variable = expression ? "the expression was true" : "the expression was false".
This is equivalent to
if(expression){
$variable="the expression is true";
}else{
$variable="the expression is false";
}
You can also nest these
$x = (expression1) ?
(expression2) ? "expression 1 and expression 2 are true" : "expression 1 is true but expression 2 is not" :
(expression2) ? "expression 2 is true, but expression 1 is not" : "both expression 1 and expression 2 are false.";
That statement won't do anything as written.
On the other hand something like
$w = isset($x) ? $y : $z;
is more meaningful. If $x satisfies isset(), $w is assigned $y's value. Otherwise, $w is assigned $z's value.
It means if $x
variable is not set , then value of $y
is assigned to $x
, else value of $z
is assigned to $x
.
It's shorthand for a single expression if/else block.
$v = isset($x) ? $y : $z;
// equivalent to
if (isset($x)) {
$v = $y;
} else {
$v = $z;
}