understading the ternary operator in php

一世执手 提交于 2019-12-24 17:19:03

问题


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


回答1:


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



回答2:


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.




回答3:


Think of it this way

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

So,

echo condition ? TRUE : FALSE;

if that makes sense




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/20747509/understading-the-ternary-operator-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!