0

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? :)

Community
  • 1
  • 1
aborted
  • 4,481
  • 14
  • 69
  • 132
  • 2
    http://php.net/manual/language.operators.comparison.php#language.operators.comparison.ternary – poke Nov 02 '10 at 21:45
  • 1
    *(related)* [What does that symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon Nov 27 '10 at 00:41

5 Answers5

14

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.

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
  • +1 for **if you don't abuse it**. I've seen many instances of nested ternary conditionals and it makes me want to cry every time. – netcoder Nov 02 '10 at 21:48
  • +1 to **if you don't abuse it**. (for the love of all that is good, DO NOT NEST!) – drudge Nov 02 '10 at 21:49
6
(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

AlcubierreDrive
  • 3,654
  • 2
  • 29
  • 45
2

It's shorthand for an if statement

You can turn that statement into this:

if ($key == $config['default_currency']) {
    $selected = ' selected="selected"';
} else {
    $selected = '';
}
Viper_Sb
  • 1,809
  • 14
  • 18
2

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 = '';
}
dan04
  • 87,747
  • 23
  • 163
  • 198
0

In pseudocode,

variable = (condition) ? statement1 : statement2

maps to

if (condition is true)
then
variable = statement1
else
variable = statement2
end if
Brian Beckett
  • 4,742
  • 6
  • 33
  • 52