In php, is 0 treated as empty?

2019-01-04 23:04发布

Code will explain more:

$var = 0;

if (!empty($var)){
echo "Its not empty";
} else {
echo "Its empty";
}

The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??

标签: php function
15条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-04 23:45

I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.

A snippet:

Expression      | empty()
----------------+--------
$x = "";        | true    
$x = null       | true    
var $x;         | true    
$x is undefined | true    
$x = array();   | true    
$x = false;     | true    
$x = true;      | false   
$x = 1;         | false   
$x = 42;        | false   
$x = 0;         | true    
$x = -1;        | false   
$x = "1";       | false   
$x = "0";       | true    
$x = "-1";      | false   
$x = "php";     | false   
$x = "true";    | false   
$x = "false";   | false   

Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure

查看更多
祖国的老花朵
3楼-- · 2019-01-04 23:45

empty should mean empty .. whatever deceze says.

When I do

$var = '';    
$var = '0';

I expect that var_dump(empty($var)); will return false.

if you are checking things in an array you always have to do isset($var) first.

查看更多
乱世女痞
4楼-- · 2019-01-04 23:47

use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.

查看更多
闹够了就滚
5楼-- · 2019-01-04 23:48

From manual: Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string) NULL
  • FALSE array() (an empty array) var
  • $var; (a variable declared, but without a value in a class)

More: http://php.net/manual/en/function.empty.php

查看更多
走好不送
6楼-- · 2019-01-04 23:50

I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.

using empty() first and then strlen() is your best best if you need this as well, as:

if(!empty($var) && strlen($var)){
    echo '"$var" is present and has a non-falsey value!';
}
查看更多
Explosion°爆炸
7楼-- · 2019-01-04 23:52

It 's working for me!

//
if(isset($_POST['post_var'])&&$_POST['post_var']!==''){
echo $_POST['post_var'];
}

//results:
1 if $_POST['post_var']='1'
0 if $_POST['post_var']='0'
skip if $_POST['post_var']=''
查看更多
登录 后发表回答