Question

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.)

Was it helpful?

Solution

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] = '';
}

OTHER TIPS

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.

Think of it this way

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

So,

echo condition ? TRUE : FALSE;

if that makes sense

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top