Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

ternary operator - Simple PHP isset test

This below does not seem to work how I would expect it, event though $_GET['friendid'] = 55 it is returning NULL

<?PHP

$_GET['friendid'] = 55;

$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';

echo $friendid;
exit;

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As of PHP 7's release, you can use the null-coalescing operator (double "?") for this:

$var = $array["key"] ?? "default-value";
// which is synonymous to:
$var = isset($array["key"]) ? $array["key"] : "default-value";

In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).

$var = $value ?: "default-value";
// which is synonymous to:
$var = $value ? $value : "default-value";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...