Search code examples
phpcomparisonphp-7string-comparisonphp-8

empty() returns true if a zero float value was passed as string


MySQL with PHP can sometimes be annoying when decimals are returned as strings like with MYSQL functions. Is there a function to check if a variable is any of these in one?

null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", or (array)[].

empty() almost does the job but falls on these mysql decimal values sometimes returned as strings. isset() and is_null() operates differently in PHP 7 and 8. I am missing something like emptyish().

What does not work:

if (empty($var)) // Doesn't work for decimal/floats passed as string "0.00"
if ($var == 0) // Leaves a warning if $var is not declared

Solution

  • This zero/empty condition works the same way in both PHP 7 and 8 versions:

    if (empty($var) || (is_numeric($var) && (float)$var == 0))
    

    It checks if $var is any of the following: not set, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", or (array)[]

    And to substitute empty():

      // Checks if variable is not set, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[], or array with nil nodes
    function nil(&$var) { // https://www.dictionary.com/browse/nil
      return (empty($var) || (is_numeric($var) && (float)$var == 0));
    }
    

    To be used like:

    if (nil($var)) {
      echo 'The value is either not set, an empty string, empty array, null, or equals zero.';
    }
    

    It can be expanded to check subnodes for arrays as well:

      // Checks if variable is not set, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[], or array with nil nodes
      function nil(&$var) {
        if (is_array($var)) {
          foreach ($var as $node) {
            if (!nil($node)) return !1;
          }
        }
        return (empty($var) || (is_numeric($var) && (float)$var == 0));
      }