PHP检查字符串是否为空的最佳方法

时间:2022-12-19 07:22:50

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?

第二种方法有什么问题吗?我应该注意哪些铸造问题?

8 个解决方案

#1


25  

if(empty($stringvar))
{
    // do something
}

You could also add trim() to eliminate whitespace if that is to be considered.

您还可以添加trim()以消除空白(如果要考虑)。

Edit:

编辑:

Note that for a string like '0', this will return true, while strlen() will not.

请注意,对于像'0'这样的字符串,这将返回true,而strlen()则不会。

#2


13  

You need isset() in case $str is possibly undefined:

如果$ str可能未定义,则需要isset():

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。

#3


6  

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));
}

#4


3  

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.

如Gras Double所述,当$ str为'0'时,上面的代码将返回true。所以这个解决方案也不能很好地工作。

#5


2  

According to PHP empty() doc (http://ca1.php.net/empty):

根据PHP empty()doc(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。

#6


1  

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()的全部目的。

#7


1  

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 page for more details.

isset($ var)和empty($ var)结果基于变量的类型,在某些情况下可能很棘手(如空字符串“”)。查看此页面中的表格以获取更多详细信息。

UPDATE

UPDATE

There are actually 2 cases for this question:

这个问题实际上有2个案例:

Case 1: You're sure that your variable is always going 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 not be 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(如果您在相同条件下测试多于1个字符串特别有用),我使其成为函数:

function isNonEmptyString($var) {
    return is_string($var) && $var !== '';
}


// Somewhere else..
// Reducing conditions to half
if(isNonEmptyString($var1) && isNonEmptyString($var2) && isNonEmptyString($var3)) {
    // do something
}

#8


-3  

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,以及它是否为空。

#1


25  

if(empty($stringvar))
{
    // do something
}

You could also add trim() to eliminate whitespace if that is to be considered.

您还可以添加trim()以消除空白(如果要考虑)。

Edit:

编辑:

Note that for a string like '0', this will return true, while strlen() will not.

请注意,对于像'0'这样的字符串,这将返回true,而strlen()则不会。

#2


13  

You need isset() in case $str is possibly undefined:

如果$ str可能未定义,则需要isset():

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。

#3


6  

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));
}

#4


3  

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.

如Gras Double所述,当$ str为'0'时,上面的代码将返回true。所以这个解决方案也不能很好地工作。

#5


2  

According to PHP empty() doc (http://ca1.php.net/empty):

根据PHP empty()doc(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。

#6


1  

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()的全部目的。

#7


1  

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 page for more details.

isset($ var)和empty($ var)结果基于变量的类型,在某些情况下可能很棘手(如空字符串“”)。查看此页面中的表格以获取更多详细信息。

UPDATE

UPDATE

There are actually 2 cases for this question:

这个问题实际上有2个案例:

Case 1: You're sure that your variable is always going 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 not be 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(如果您在相同条件下测试多于1个字符串特别有用),我使其成为函数:

function isNonEmptyString($var) {
    return is_string($var) && $var !== '';
}


// Somewhere else..
// Reducing conditions to half
if(isNonEmptyString($var1) && isNonEmptyString($var2) && isNonEmptyString($var3)) {
    // do something
}

#8


-3  

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,以及它是否为空。