TecBrat
TecBrat

Reputation: 3729

understading the ternary operator in php

I'm reading someone else's code and they have a line like this:

  $_REQUEST[LINKEDIN::_GET_TYPE] = (isset($_REQUEST[LINKEDIN::_GET_TYPE])) ? $_REQUEST[LINKEDIN::_GET_TYPE] : '';

I just want to make sure I follow this. I might have finally figured out the logic of it.

Is this correct?

If $_REQUEST[LINKEDIN::_GET_TYPE] is set, then assign it to itself. (meant as a do-nothing condition) otherwise set it to a null string. (Would imply that NULL (undefined) and "" would not be treated the same in some other part of the script.)

Upvotes: 1

Views: 116

Answers (5)

Joe
Joe

Reputation: 1394

Your explanation is correct as far as my knowledge goes.

A ternary operator is like an if statement. The one you have would look like this as an if statement:

if( isset($_REQUEST[LINKEDIN::_GET_TYPE] ) {
    $_REQUEST['LINKEDIN::_GET_TYPE] = $_REQUEST['LINKEDIN::_GET_TYPE];
} else {
    $_REQUEST['LINKEDIN::_GET_TYPE] = ''; // It equals an empty string, not null.
}

Sometimes its easier to look at a ternary statement like a normal if statement if you are unsure on what is going on.

The statement you have seems to be doing what you say, setting the value to its self if it is set, and if it is not set, setting it to an empty string.

Upvotes: 0

Marc B
Marc B

Reputation: 360692

This

$foo = $bar ? 'baz' : 'qux';

is the functional equivalent of

if ($bar) { // test $bar for truthiness
   $foo = 'baz';
} else {
   $foo = 'qux';
}

So yes, what you're doing would work. However, with the newer PHP versions, there's a shortcut version of the tenary:

$foo = $bar ?: 'qux';

which will do exactly what you want

Upvotes: 1

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

Think of it this way

if(condition) { (?)
   //TRUE
} else { (:)
   //FALSE
}

So,

echo condition ? TRUE : FALSE;

if that makes sense

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

The ternary operator you posted acts like a single line if-else as follows

if (isset($_REQUEST[LINKEDIN::_GET_TYPE])) {
  $_REQUEST[LINKEDIN::_GET_TYPE] = $_REQUEST[LINKEDIN::_GET_TYPE];
} else {
  $_REQUEST[LINKEDIN::_GET_TYPE] = '';
}

Which you could simplify as

if (!(isset($_REQUEST[LINKEDIN::_GET_TYPE]))) {
  $_REQUEST[LINKEDIN::_GET_TYPE] = '';
}

Upvotes: 6

Kermit
Kermit

Reputation: 34055

You missed the last part. If $_REQUEST[LINKEDIN::_GET_TYPE] is not set, then $_REQUEST[LINKEDIN::_GET_TYPE] is set to empty, not null. The point is that when $_REQUEST[LINKEDIN::_GET_TYPE] is called, that it exists but has no value.

Upvotes: 1

Related Questions