Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In php, is 0 treated as empty?

Tags:

function

php

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"??

like image 888
mysqllearner Avatar asked Feb 08 '10 09:02

mysqllearner


People also ask

Is 0 an empty string?

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

What is considered empty in PHP?

PHP empty() FunctionThe empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

Is null the same as 0 in PHP?

NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false . Show activity on this post. Null is nothing, False is a bit, and 0 is (probably) 32 bits.

Is empty string in PHP?

We can use empty() function to check whether a string is empty or not. The function is used to check whether the string is empty or not. It will return true if the string is empty. Parameter: Variable to check whether it is empty or not.


2 Answers

http://php.net/empty

The following things are considered to be empty:

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

Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.

like image 128
deceze Avatar answered Sep 21 '22 16:09

deceze


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) ----------------+-------- $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

like image 30
Dan Soap Avatar answered Sep 20 '22 16:09

Dan Soap