PHP handled "0" as empty?

I ran into a problem when php handles "0" differently.

I run the following script on two different machines:

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

1) Local machine -> PHP 5.2.17 -> it treated "0" as valid and printed "helo"

2) Server -> PHP 5.3.6 -> it treated "0" as empty / false and does not print "helo"

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

+6
source share
4 answers

The way it is supposed to. PHP interprets strings in a boolean context. "0" equivalent to the actual 0 . (See also http://www.php.net/manual/en/types.comparisons.php )

What you wanted to check is possible:

 if (strlen($a)) { 
+5
source

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

+2
source

Sounds weird to me, I thought β€œ0” was false, you can view it here

0
source

PHP can bind "0" as false, since it will be null / false / 0.

However, it can also bind it as a string "0". Thus, the if statement will return true, however, I think it will be an error if you do not draw it (string).

As Mario said, check for strlen ($ a) or check if there is (! Empty ($ a)) so that you get the final answer.

Hope this helps!

0
source

Source: https://habr.com/ru/post/904298/


All Articles