Possible Duplicate:
What is the PHP ? : operator called and what does it do?
I found the answer to something I was looking for, but I don't quite understand the syntax because they used, I think, short tags. Here is the code:
$temp = is_array($value) ? $value : trim($value);
Could someone explain how this works? I think this means if true, return the value and if false return the value trimmed, but I'm not sure. Can there be more than two options, or is it strictly true and false?
You are correct. This is a conditional operator, ?:
is a ternary operator.
<?php
// Example usage for: Ternary Operator
$temp = is_array($value) ? $value : trim($value);
// The above is identical to this if/else statement
if (is_array($value)) {
$temp = $value;
} else {
$temp = trim($value);
}
?>
Take a look half way down this page for more information:
It is equivalent to
if (is_array($value)){
$temp = $value;
}
else{
$temp = trim($value);
}
It's basically the same as
if(is_array($value)) {
$temp = $value;
} else {
$temp = trim($value);
}
$condition ? true : false
, the ?
instruction is same as
if($condition)
true
else
false
so in your example the code is same as
if(is_array($value))
$temp = $value
else
$temp = trim($value);
You are correct. If is_array($value)
returns true then the expression sets $temp = $value
otherwise $temp = trim($value)
.
Strictly two choices. You interpreted it correctly.
if (is_array($value)) $temp = $value;
else $temp = trim($value);
If you wanted to hack this syntax to have 3 values you could do $temp = (condition1) ? true : (condition2) ? true2 : false;
This is ternary operator. Its will convert exp before ? to a bool. If you want more option just combine multi ?:.
(con?trueorfalseiftrue:otherwise)? (con2?_:_):(con3?_:_)