0

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?

Community
  • 1
  • 1
  • Also: [Reference - What does this symbol mean in PHP ?: & =& !! @ :: => -> >> ++ .=](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – mario Dec 07 '10 at 02:23

7 Answers7

3

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:

http://php.net/manual/en/language.operators.comparison.php

David Hancock
  • 14,191
  • 4
  • 38
  • 44
  • It is known as *the* ternary operator so long as `.` is known as *the* binary operator :P – alex Dec 07 '10 at 02:18
1

It is equivalent to

if (is_array($value)){
    $temp = $value;
}
else{
    $temp = trim($value);
}

More info: http://en.wikipedia.org/wiki/Ternary_operation

Ives.me
  • 2,198
  • 15
  • 21
1

$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);
RageZ
  • 25,094
  • 11
  • 63
  • 76
0

It's basically the same as

if(is_array($value)) {
   $temp = $value;
} else {
   $temp = trim($value);
}
Andreas Wong
  • 55,398
  • 19
  • 100
  • 120
0

You are correct. If is_array($value) returns true then the expression sets $temp = $value otherwise $temp = trim($value).

Matt Phillips
  • 10,125
  • 10
  • 42
  • 69
0

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;

Mikhail
  • 8,071
  • 6
  • 45
  • 78
  • Indeed, though probably worthwhile to add parentheses for clearer grouping: `$temp = $condition1 ? 'val1' : ($condition2 ? 'val2' : 'val3');` And some people argue that chaining the ternary operator this way is inherently hard to read. YMMV. ;-) – David Weinraub Dec 07 '10 at 03:23
0

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?_:_)
pinichi
  • 2,159
  • 15
  • 17