1

可能是一个愚蠢的问题,但我似乎无法找到一个直接的答案。

$id != ""一样的!empty($id)吗?

if(isset($id) && !empty($id))用于确定变量是否已设置且不为空/空是否正确?

4

5 回答 5

6

No. empty() covers many other conditions besides an empty string. http://php.net/manual/en/function.empty.php From the documentation:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

Also, if you want to tell if a variable "empty", then just empty() is needed. No need for isset() as well.

于 2013-06-10T00:55:32.707 回答
2

哼:简而言之,

if($var)意味着,如果$var是或具有TRUE的值,

另一方面,if(!$var)表示如果$var值为FALSE

if(empty($var))同样if(!empty($var))尝试检查是否$var有任何值,或者它们是否为空。

$var = ''; // false 
$var = '1' // true
$var; // empty
$var = '1' // not empty

更多信息,请访问 PHP手册

一些例子包括:

<?php
var_dump((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>
于 2013-06-10T00:57:17.710 回答
1

empty will just return true for undefined variables, so there's no need to double check it.

Just use if ( ! empty($id) )

于 2013-06-10T00:55:19.560 回答
1

$id != "" 和 !empty($id) 一样吗?

不,empty测试所有形式的空。所以它也会在0or上触发null。与空字符串比较 using!=将根据 的字符串转换进行比较$id

使用 if(isset($id) && !empty($id)) 来确定变量是否已设置并且不为空/空是否正确?

不是真的,这个条件只是测试$idset 是否不包含空字符串、字符串"0"、整数/浮点0值,或者任何可以转换为整数的东西,0例如 boolean false

PHP.net上有一个非常详尽的列表,其中考虑了哪些值empty

于 2013-06-10T00:56:37.983 回答
0

Firstly, no $id != "" is not the same as !empty($id). The difference is that if $id is not set then the first example will throw a notice that you're using an undefined variable and the second one wont.

Secondly, it is correct if you use both isset() and empty() but it's redundant since empty will not throw a notice if the variable is undefined.

Hope that was helpful to you!

Good luck and happy coding :P

于 2013-06-10T00:56:14.653 回答