Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP treated "0" as empty?

Tags:

php

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?

like image 480
TonyTakeshi Avatar asked Dec 22 '11 09:12

TonyTakeshi


People also ask

Does 0 count as empty PHP?

The following things are considered to be empty: "" (an empty string) 0 (0 as an integer) "0" (0 as a string) NULL.

Is 0 an empty string?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

What is considered empty in PHP?

A variable is considered empty if it does not exist or if its value equals false .

Should I use empty PHP?

You should use the empty() construct when you are not sure if the variable even exists. If the variable is expected to be set, use if ($var) instead. empty() is the equivalent of ! isset($var) || $var == false .


1 Answers

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)) {
like image 96
mario Avatar answered Oct 13 '22 10:10

mario