6

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?

1
  • 4
    PHP 5.2.17 (Win32) does not print "helo" when $a = "0"; (just tested it on CLI and through Apache to make sure). You must have had another character in the string as well - maybe a whitespace character that was invisible when printed, like \r? Commented Dec 22, 2011 at 9:09

4 Answers 4

5

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)) {
Sign up to request clarification or add additional context in comments.

1 Comment

But it didn't do it in PHP 5.2.17 ?
2

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.)

Comments

0

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

Comments

0

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.