null null - 6 months ago 23
PHP Question

Fixing the PHP empty function

PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the

empty()
function. This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc?

Answer

This didn't work for me.

if (empty($variable) && '0' != $variable) {
  // Do something
}

I used instead:

if (empty($variable) && strlen($variable) == 0) {
  // Do something
}
Comments