php PHP检查字符串是否为空的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4531288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP best way to check whether a string is empty or not
提问by Yada
I've seen a lot of php code that does the following to check whether a string is valid by doing:
我见过很多 php 代码,它们执行以下操作来检查字符串是否有效:
$str is a string variable.
$str 是一个字符串变量。
if (!isset($str) || $str !== '') {
// do something
}
I prefer to just do
我更喜欢做
if (strlen($str) > 0) {
// something
}
Is there any thing that can go wrong with the second method? Are there any casting issues I should be aware of?
第二种方法有什么问题吗?有什么我应该注意的铸造问题吗?
回答by JYelton
Since PHP will treat a string containing a zero ('0') as empty, it makes the empty()
function an unsuitablesolution.
由于 PHP 会将包含零 ('0') 的字符串视为空字符串,因此该empty()
函数成为不合适的解决方案。
Instead, test that the variable is explicitlynot equal to an empty string:
相反,测试变量是否显式不等于空字符串:
$stringvar !== ''
$stringvar !== ''
As the OPand Gras Doubleand others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings):
正如OP和Gras Double和其他人所示,还应检查变量的初始化以避免警告或错误(取决于设置):
isset($stringvar)
isset($stringvar)
This results in the more acceptable:
这导致更容易接受:
if (isset($stringvar) && $stringvar !== '') {
}
PHP has a lot of bad conventions. I originally answered this (over 9 years ago) using the empty()
function, as seen below. I've long since abandoned PHP, but since this answer attracts downvotes and comments every few years, I've updated it. Should the OP wish to change the accepted answer, please do so.
PHP 有很多不好的约定。我最初使用该empty()
函数回答了这个问题(9 多年前),如下所示。我早就放弃了 PHP,但由于这个答案每隔几年就会吸引反对票和评论,我已经更新了它。如果 OP 希望更改已接受的答案,请这样做。
Original Answer:
原答案:
if(empty($stringvar)) { // do something }
You could also add
trim()
to eliminate whitespace if that is to be considered.Edit:
Note that for a string like '
0
', this will return true, whilestrlen()
will not.
if(empty($stringvar)) { // do something }
trim()
如果要考虑,您还可以添加以消除空格。编辑:
请注意,对于像 '
0
' 这样的字符串,这将返回 true,而strlen()
不会。
回答by Gras Double
You need isset()
in case $str
is possibly undefined:
您需要isset()
在情况下$str
可能是不确定的:
if (isset($str) && $str !== '') {
// variable set, not empty string
}
Using !empty()
would have an important caveat: the string '0'
evaluates to false.
使用!empty()
会有一个重要的警告:字符串的'0'
计算结果为 false。
Also, sometimes one wants to check, in addition, that $str
is not something falsy, like false
or null
[1]. The previous code doesn't handle this. It's one of the rare situations where loose comparison may be useful:
此外,有时人们还想检查一下,这$str
不是虚假的东西,例如false
或null
[1]。前面的代码不处理这个。这是松散比较可能有用的罕见情况之一:
if (isset($str) && $str != '') {
// variable set, not empty string, not falsy
}
The above method is interesting as it remains concise and doesn't filter out '0'
. But make sure to document your code if you use it.
上面的方法很有趣,因为它保持简洁并且不会过滤掉'0'
. 但是,如果您使用它,请确保记录您的代码。
Otherwise you can use this equivalent but more verbose version:
否则,您可以使用此等效但更详细的版本:
if (isset($str) && (string) $str !== '') {
// variable set, not empty string, not falsy
}
Of course, if you are sure $str
is defined, you can omit the isset($str)
from the above codes.
当然,如果你确定$str
定义了,你可以isset($str)
从上面的代码中省略。
Finally, considering that '' == false
, '0' == false
, but '' != '0'
, you may have guessed it: PHP comparisons aren't transitive(fun graphs included).
最后,考虑到'' == false
, '0' == false
, 但是'' != '0'
,您可能已经猜到了:PHP 比较不是可传递的(包括有趣的图表)。
[1] Note that isset()
already filters out null
.
[1] 请注意,isset()
已经过滤掉了null
.
回答by Peter Gluck
This will safely check for a string containing only whitespace:
这将安全地检查只包含空格的字符串:
// Determines if the supplied string is an empty string.
// Empty is defined as null or containing only whitespace.
// '0' is NOT an empty string!
function isEmptyString($str) {
return !(isset($str) && (strlen(trim($str)) > 0));
}
回答by Marco Demaio
What about this:
那这个呢:
if( !isset($str[0]) )
echo "str is NULL or an empty string";
I found it on PHP manual in a comment by Antone Roundy
我在Antone Roundy的评论中在 PHP 手册上找到了它
I posted it here, because I did some tests and it seems to work well, but I'm wondering if there is some side effect I'm not considering. Any suggestions in comments here would be appreciated.
我把它贴在这里,因为我做了一些测试,它似乎运行良好,但我想知道是否有一些我没有考虑的副作用。在这里评论中的任何建议将不胜感激。
Edit:
编辑:
As noted by Gras Double, when $str
is '0'
the code above will return true. So this solution does not work well either.
正如节双指出,当$str
是'0'
上面的代码将返回true。所以这个解决方案也不能很好地工作。
回答by evilReiko
This simple old question is still tricky.
这个简单的老问题仍然很棘手。
strlen($var)
works perfectly ONLY if you're absolutely sure the $var is a string.
strlen($var)
只有当您绝对确定 $var 是一个字符串时,它才能完美运行。
isset($var)
and empty($var)
result are based on type of the variable, and could be tricky at some cases (like empty string ""). View the table in this pagefor more details.
isset($var)
和empty($var)
结果基于变量的类型,在某些情况下可能会很棘手(例如空字符串“”)。查看此页面中的表格以获取更多详细信息。
UPDATE
更新
There are actually 2 cases for this question:
这个问题实际上有两种情况:
Case 1: You're sure that your variable is alwaysgoing to be a "string":
案例 1:您确定您的变量始终是“字符串”:
In this case, just test the length:
在这种情况下,只需测试长度:
if(strlen($str) > 0) {
// do something..
}
Case 2: Your variable may and may notbe a "string":
情况 2:您的变量可能是也可能不是“字符串”:
In this case, it depends on what you want to do. For me (most of the time), if it's not a string then I validate it as "false". You can do it this way:
在这种情况下,这取决于您想要做什么。对我来说(大部分时间),如果它不是字符串,那么我将其验证为“false”。你可以这样做:
if(is_string($var) && $var !== '') {// true only if it's a string AND is not empty
// do something ...
}
And to make it shorter and in 1 condition instead of 2 (specially useful if you're testing more than 1 string in same if condition), I made it into function:
为了使它更短,并在 1 个条件而不是 2 个条件下(如果您在相同的 if 条件下测试超过 1 个字符串特别有用),我将其设置为函数:
function isNonEmptyString($var) {
return is_string($var) && $var !== '';
}
// Somewhere else..
// Reducing conditions to half
if(isNonEmptyString($var1) && isNonEmptyString($var2) && isNonEmptyString($var3)) {
// do something
}
回答by Hugues Lavoie
According to PHP empty() doc (http://ca1.php.net/empty):
根据 PHP empty() 文档(http://ca1.php.net/empty):
Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
Instead, use trim($name) == false.
在 PHP 5.5 之前,empty() 只支持变量;其他任何事情都会导致解析错误。换句话说,以下将不起作用:empty(trim($name))。
相反,使用 trim($name) == false。
回答by Jake Wilson
If your variable $str
is not defined then your strlen()
method will throw an exception. That is the whole purpose of using isset()
first.
如果您的变量$str
未定义,那么您的strlen()
方法将引发异常。这就是使用isset()
first的全部目的。
回答by Sebastjan
I think not, because strlen (string lenght) returns the lenght (integer) of your $str variable. So if the variable is empty i would return 0. Is 0 greater then 0. Don't think so. But i think the first method might be a little more safer. Because it checks if the variable is init, and if its not empty.
我认为不是,因为 strlen (string lenght) 返回 $str 变量的长度 (整数)。因此,如果变量为空,我将返回 0。0 是否大于 0。不要这么认为。但我认为第一种方法可能更安全一些。因为它会检查变量是否为 init,以及是否为空。