2

I found this line of code and I'm trying to comprehend what it's doing. The part I'm not familiar with is the question mark and the colon. What are these characters used for?

$string = $array[1] . ($array[0] === 47 ? '' : ' word');
Josh Leitzel
  • 14,093
  • 12
  • 57
  • 76
Andrew
  • 196,883
  • 184
  • 487
  • 673
  • This is the conditional operator. It is also a type of ternary operator (simply because it has 3 operands) and often folks make the mistake of calling it _the_ ternary operator which doesn't really make a whole lot of sense. – Andrew Hare Oct 29 '09 at 06:18
  • Also this is a duplicate, please see http://stackoverflow.com/questions/889373/quick-php-syntax-question and http://stackoverflow.com/questions/1276909/php-syntax-question-what-does-the-question-mark-and-colon-mean. – Andrew Hare Oct 29 '09 at 06:20
  • @Andrew -- silly or not, the PHP manual has named this construct The Ternary Operator, so it's not a mistake to refer to it as such http://php.net/manual/en/language.operators.comparison.php – Alan Storm Oct 29 '09 at 06:26
  • See http://stackoverflow.com/questions/80646/how-do-the-equality-and-identity-comparison-operators-differ for your next question. :) – Greg Hewgill Oct 29 '09 at 06:28

2 Answers2

5

That's a ternary operator; basically a short-hand conditional.

It's the same as:

$string = $array[1];

if ($array[0] !== 47)
    $string .= ' word';

See this section in the PHP manual (the "Ternary Operator" section).

Josh Leitzel
  • 14,093
  • 12
  • 57
  • 76
0

That's the ternary operator.

Here's a reference to a tutorial

It works somehow like this:

function tern()

    if ($array[0] === 47)
    {
        return '';
    }
    else
    {
        return 'word';
    }
}
Teej
  • 12,352
  • 9
  • 68
  • 92