1

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?

Community
  • 1
  • 1
John
  • 877
  • 5
  • 14
  • 21
  • possible duplicate of [What is the PHP ? : operator called and what does it do?](http://stackoverflow.com/questions/1080247/what-is-the-php-operator-called-and-what-does-it-do) (along with several others linked from the [Stackoverflow PHP Wiki Page](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php). – Quentin Nov 29 '11 at 22:32

5 Answers5

8

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
Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
2

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.";
bigblind
  • 12,539
  • 14
  • 68
  • 123
2

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.

joadha
  • 191
  • 1
  • 15
0

It means if $x variable is not set , then value of $y is assigned to $x , else value of $z is assigned to $x.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

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;
}
Daren Chandisingh
  • 2,157
  • 1
  • 13
  • 17