设置或不设置哪个更好?
之间有速度差异吗
if (isset($_POST['var']))
或
if ($_POST['var'])
?哪个更好还是相同?
Is there any speed difference between
if (isset($_POST['var']))
or
if ($_POST['var'])
And which is better or are they the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
出于以下原因,最好使用
isset
:$_POST['var']
是空字符串或"0"
,isset
仍会检测到该变量存在。It is a good practice to use
isset
for the following reasons:$_POST['var']
is an empty string or"0"
,isset
will still detect that the variable exists.他们不一样。 考虑一个概念数组:
假设
$x
是这些键之一('a' 到 'f'),并且键 'g' 不存在,它的工作方式如下:$arr对于所有键 a 到 g,[$x]
为false
;isset($arr[$x])
为true
,但对于 e 和 g,false
; 。array_key_exists($x, $arr)
为true
,对于 g,false
我建议你看看 PHP 的类型杂耍,特别是布尔值的转换。
最后,您所做的称为<a href="http://www.codinghorror.com/blog/archives/000185.html" rel="noreferrer">微优化。 永远不要选择其中哪一个被认为更快。 无论哪个更快,差异都可以忽略不计,即使您可以可靠地确定哪个更快(我不确定您是否可以达到任何统计显着水平),它也不应该成为一个因素。
They aren't the same. Consider a notional array:
Assuming
$x
is one of those keys ('a' to 'f') and the key 'g' which isn't there it works like this:$arr[$x]
isfalse
for all keys a to g;isset($arr[$x])
istrue
for keys a, b, c, d and f butfalse
for e and g; andarray_key_exists($x, $arr)
istrue
for all keys a to f,false
for g.I suggest you look at PHP's type juggling, specifically conversion to booleans.
Lastly, what you're doing is called micro-optimization. Never choose which one of those by whichever is perceived to be faster. Whichever is faster is so negligible in difference that it should never be a factor even if you could reliably determine which is faster (which I'm not sure you could to any statistically significant level).
isset
测试变量是否具有任何值,而 if 测试变量的值。例如:
最大的问题是两个表达式的等价性取决于您正在检查的变量的值,因此您不能做出假设。
isset
tests that the variable has any value, while the if tests the value of the variable.For example:
The big problem is that the equivalency of the two expressions depends on the value of the variable you are checking, so you can't make assumptions.
在严格的 PHP 中,您需要在使用变量之前检查它是否已设置。
您在这里所做的
if($var)
不检查该值是否已设置。 因此,Strict PHP 将为未设置的变量生成通知。 (这种情况在数组中经常发生)
此外,在严格的 PHP 中(仅供您或其他人参考),在函数中使用未设置的 var 作为参数将引发通知,并且您无法在函数中检查 isset() 来避免那。
In strict PHP, you need to check if a variable is set before using it.
What you are doing here
if($var)
Isn't checking if the value is set. So Strict PHP will generate a notice for unset variables. (this happens a lot with arrays)
Also in strict PHP (just an FYI for you or others), using an unset var as an argument in a function will throw a notice and you can't check isset() within the function to avoid that.
只是重复别人所说的,如果你执行:
并且 $variable not 设置,你会收到一个通知错误。 另外..
但在这种情况下使用 isset 将返回 true 。
Just repeating what others said, if you execute:
and $variable is not set, you'll get a notice error. Plus..
but using isset would return true in this case.