What is this called? A: ternary operator

Suzanne's picture

She has: 5,507 posts

Joined: Feb 2000

I want to learn more about this:

$address_primary==$alabel ? 'y' : '';

What is it called?

Suzanne's picture

She has: 5,507 posts

Joined: Feb 2000

ternary operator is what it's called. Whee! nevermind. Smiling

http://uk.php.net/language.operators.comparison for more info (it's the example)

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

lol

It operates exactly like this:
if (condition) { true_statement } else { false_statement }

I find it very usefull for inline conditions. For example, making things plural...
echo $months.' month'.($months==1 ? '' : 's');

possible ouputs:
0 months
1 month
2 months
3 months

Mark Hensler
If there is no answer on Google, then there is no question.

Suzanne's picture

She has: 5,507 posts

Joined: Feb 2000

It seems rather handy. I'm playing around with it to make the code a little more sensible. All the if/else statements get a little l-o-o-o-n-g for short things.

Vincent Puglia's picture

They have: 634 posts

Joined: Dec 1999

Hi Suzanne,

It's the same in javascript:

var myVar = (conditional) ? trueStatement : falseStatement;

btw: that makes 3 blackouts for me (65,77,03) Smiling
Vinny

Where the world once stood
the blades of grass cut me still

Suzanne's picture

She has: 5,507 posts

Joined: Feb 2000

I wasn't around for 65, on the wrong side for 77, lucky me, moved back for 03.

I was trying to find out what it was called because I couldn't dig up information without the real term. I wanted to see if I could, er, force it to do something else. Wink (I can't -- but I figured it out anyway).

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.