Jump to content

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;

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.