Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Basics (Retired) PHP Operators Operators

Shazad Kazi
Shazad Kazi
10,758 Points

Single Ternary Operator :? :S Confused

Can someone please explain this and preferably create another example. I'm just trying to get my head around it and want to make sure.

there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator).

echo $a === $b? $a : 'not equal';
//displays $a if $a is equal to $b

2 Answers

Hi Shazad,

As I understand them a single ternary operator is short hand for If Then Else

$var = 10;
$var_greater_than_five = ($var > 5 ? true : false);

This is another way of saying:

$var = 10;
if ($var > 5 ) {
    $var_greater_than_five = true;
}else{
    $var_greater_than_five = false;
}

They both do the same thing, just one is faster to type. Some devs seem to use them a lot and others not at all, it's personal preference.

Ternary operators can be tricky to read if long and complex, so my rule is I won't use them unless they will fit in a single 80 char line. i tend to only use them for setting a boolean value - again personal preference.

Hope that helps.

KB :octopus:

Joel Bardsley
Joel Bardsley
31,249 Points

A simple, but common, use would be a message at the top of the page that is different depending on whether the user is logged in. For example:

$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');

Using the above shorthand is the equivalent of running an if/else statement like:

$message = 'Hello ';
if ($user->is_logged_in()) {
  $message .= $user->get('first_name'); // "Hello Shazad"
} else {
  $message .= 'Guest'; // "Hello Guest"
}

So if $user->is_logged_in() is true, the code between the ? and the : is run, otherwise the code after the : is run.