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 e.g.,
$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 . "
";
$_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
yes you would do it like this
$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';
something like this:
$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 e.g.
function isset_or(&$variable, $default = NULL)
{
return isset($variable) ? $variable : $default;
}
$foo = isset_or($_GET['bar'], 'hello');