PHP将“0”视为空?

I have encounteed an issue with php treating "0" differently.

I run following script on 2 different machines:

$a = "0";
if ($a) {
    echo("helo");
}

1) Local Machine -> PHP 5.2.17 -> it treated "0" as valid and print the 'helo'

2) Server -> PHP 5.3.6 -> it treated "0" as empty/false and won't print the 'helo'

Is this due to the php configuration (if yes, what configuration) or php version?

php
dqu92800
dqu92800 当$a=“0”时,PHP5.2.17(Win32)不会打印“helo”;(只是在CLI和Apache上测试它以确保)。你必须在字符串中有另一个字符-也许是一个在打印时看不见的空白字符,比如 ?
接近 9 年之前 回复

4个回答



这就是它应该如何。 PHP在布尔上下文中解释字符串。 “0”</ code>相当于实际的 0 </ code>。 (另请参见 http://www.php.net/manual/en/types.comparisons.php</ a>)</ p>

您打算测试的可能是:</ p>

  if(strlen($ a)){
</ 代码> </ pre>
</ div>

展开原文

原文

That's how it is supposed to. PHP interprets strings in boolean context. The "0" there is equivalent to an actual 0. (See also http://www.php.net/manual/en/types.comparisons.php)

What you meant to test for is probably:

if (strlen($a)) {

doyhq66282
doyhq66282 但它在PHP 5.2.17中没有这样做?
接近 9 年之前 回复

if($a) should be FALSE, as per the documentation. It should also be like that on your local machine. Are you sure that on the local machine, you don't have a space after the 0 or something? ("0<space>" would be TRUE.)



声音奇怪,我认为“0”是假的,你可以查看这里 </ p>
</ div>

展开原文

原文

Sound weird to me, I thought "0" was false, you can review here



PHP可能会将“0”插入为false,因为它与null / false / 0等效。</ p>

但是,它也可以将其插入为“0”字符串。 因此,if语句将返回true,但是,我认为这将是一个bug,除非你输入它(string)。</ p>

像Mario说的那样,检查strlen($ a) 或检查是否(!空($ a))这样你会得到明确的答案。</ p>

我希望这有帮助!</ p>
</ div>

展开原文

原文

PHP may interporate "0" as false as it would be equivilent to null/false/0.

However, it also may interporate it as a string of "0". Thus the if statement would return true, however, I think that would be a bug unless you type cast it to (string).

Like Mario said, check for the strlen($a) or check if( !empty($a) ) that way you will get your definitive answer.

I hope this helps!

立即提问