In php, is 0 treated as empty? In php, is 0 treated as empty? php php

In php, is 0 treated as empty?


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.


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


In case of numeric values you should use is_numeric function:

$var = 0;if (is_numeric($var)){  echo "Its not empty";} else {    echo "Its empty";}