简体   繁体   中英

Get value of variable when isset() is used in PHP ternary shorthand operator

In using the shorter ternary operator:

$foo = isset($_GET['bar']) ?: 'hello';

If $_GET['bar'] is set, is it possible for $foo to return the value of $_GET['bar'] instead of true ?

Edit: I understand the old school ternary works eg,

$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';

but I want to use the newschool ternary which is the even shorter version

It sounds like you are asking about the new (as of PHP 7) null coalesce operator . You can do something like:

$foo = $_GET['bar'] ?? 'hello';
echo $foo;

Which if $_GET['bar'] is null will set $foo to hello .

The first operand from left to right that exists and is not NULL. NULL if no values are defined and not NULL. Available as of PHP 7.

Functional demo: https://3v4l.org/0CfbE

$foo = $_GET['bar'] ?? 'hello';
echo $foo . "\n";
$_GET['bar'] = 'good bye';
$foo = $_GET['bar'] ?? 'hello';
echo $foo;

Output:

hello
good bye

Additional reading on it: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

是的,你会这样做

$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';

像这样的东西:

$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';

I'm not sure I understand your question, but is it something like:

$foo = isset($_GET['bar']) ? true : 'hello';

This will give you one(true) if that variable is set or just hello if it's not.

The answer is no (in PHP5 at least, see chris's answer for PHP7 only). For this reason I tend to use a helper function eg

function isset_or(&$variable, $default = NULL)
{
    return isset($variable) ? $variable : $default;
}

$foo = isset_or($_GET['bar'], 'hello');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM