tags:

views:

713

answers:

4

The empty() native in PHP will fail if the string is "0" or something like that.

So how to implement the exact is_empty() function in PHP?

A: 

Quite simple, check for the error case described above. If you run into it, return the result you want. If not, call empty() and return that result.

Douglas Mayle
+2  A: 

try this:

function is_empty(&$val) {
  return empty($val) && $val !== "0";
}

&$val is needed, so you don’t get a warning on undefined variables.

if you only want to check if a variable is set (regardless of its value) you should use PHP’s isset

knittl
You need strict type checking, don't you? It should be Otherwise PHP can convert false and "" to 0.
FractalizeR
good catch there!
knittl
+1  A: 

You may want to use isset if you are trying to check if that variable is defined.

Cem Kalyoncu
+1  A: 

Check out the type comparison table in the PHP manual for the exact behaviour of empty(), isset(), is_null() etc. You'll probably find what you're looking for there.

christian studer