PHP中检查isset()和大于5的方式是什么?

huangapple go评论55阅读模式
英文:

What is the PHP way to check isset() and greater than 5?

问题

Here's the translated code part:

当我运行一个简单的if语句,而键未设置时,它会失败,我想知道最佳方法是如何检查键是否已设置且大于5的。这是我现在的代码:

if (isset($a['key'])) {
    if ($a['key'] > 5) {
        foo;
    }
}

我知道有一种更优雅的方法来做这个。

仅仅检查大于5会在未设置时导致错误。

if ($a['key'] > 5) {
    foo;
}

Please note that this translation may not include all the special characters (like >) from the original code, but the logic remains the same.

英文:

When I run a simple if statement and the key is not set it fails, I want to know what is the best way to check if the key is set and greater than 5. This is what I have now:

if (isset($a['key']) {
    if ($a['key'] > 5) {
        foo;
    }
}

I know there is a prettier way of doing this.

Simply checking for greater than 5 results in an error when not set.

if ($a['key'] > 5) {
    foo;
}

答案1

得分: 2

在PHP7.1之后:

如果 ($a['key'] ?? 0 > 5) {
// $a['key'] 已设置且大于5
}

英文:

Since PHP7.1

 if ($a['key'] ?? 0 > 5) {
     //  $a['key'] is set and also greater than 5
 }

huangapple
  • 本文由 发表于 2023年4月20日 00:21:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定