Jump to content

[SOLVED] Ternary operator?


Aureole

Recommended Posts

There is a great definition and example in the PHP Manual in 14. Expressions

 

I pasted lil' bit from there ::

 

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>  

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

 

The ternary operator is just an if else statement, without the words if/else, instead they are symbols instead.

 

If you understand an if/else statement you'll be able to use a ternary operator.

 

The syntax of a ternary operator is this:

(condition) ? true : false

 

The above is the same as:

if(condition) {
    true
} else {
    false
}

 

Ternary operators are inline, they cannot execute blocks of code.

I think I get it now. So is this...

 

<?php
if($_SESSION['logged_in'] == 1) {
    $this->output = 1;
}
else {
    $this->output = 0;
}
?>

 

...the same as this...

 

<?php
if($_SESSION['logged_in'] == 1) ? $this->output = 1 : $this->output = 0;
?>

 

...?

 

Also is that the correct syntax?

Don't forget ternary operators return values. So you could assign a variable a ternary operator, eg instead of doing this

($_SESSION['logged_in'] == 1) ? $this->output = 1 : $this->output = 0;

 

You can do just this:

$this->output = ($_SESSION['logged_in'] == 1) ?  1 : 0;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.