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

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

问题描述:

我看过很多php代码,它们通过执行以下操作来检查字符串是否有效:

I've seen a lot of php code that does the following to check whether a string is valid by doing:

$ str是一个字符串变量.

$str is a string variable.

if (!isset($str) || $str !== '') {
  // do something
}

我宁愿做

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?

由于PHP会将包含零('0')的字符串视为空,因此使empty()函数成为 不适合 解决方案.

Since PHP will treat a string containing a zero ('0') as empty, it makes the empty() function an unsuitable solution.

相反,测试变量 明确 不等于空字符串:

Instead, test that the variable is explicitly not equal to an empty string:

$stringvar !== ''

作为 OP

As the OP and Gras Double and others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings):

isset($stringvar)

这会导致更可接受的结果:

This results in the more acceptable:

if (isset($stringvar) && $stringvar !== '') {
}

PHP有很多不好的约定.我最初是使用empty()函数(超过9年前)回答此问题的,如下所示.我早就放弃了PHP,但是由于这个答案每隔几年就会引起人们的反对和评论,所以我已经对其进行了更新.如果OP希望更改接受的答案,请这样做.

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.

原始答案:

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

如果需要考虑的话,还可以添加trim()来消除空格.

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

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

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