php: '0' as a string with empty()

前端 未结 13 807
自闭症患者
自闭症患者 2020-12-06 04:05

I want a 0 to be considered as an integer and a \'0\' to be considered as a string but empty() considers the \'0\' as a string in the example below,

$var = \         


        
13条回答
  •  情话喂你
    2020-12-06 04:44

    empty is by far the most confusing and useless function in the php repertoire. Don't use it.

    There are three separate things you want to know when checking a value.

    • the value exists (use isset)
    • the value has a specific type (use is_xxx)
    • the value has specific properties (use comparison operators, strpos or regular expressions).

    (the last two can be combined into one with typecasts or '===').

    Examples:

    if(isset($var) && is_string($var) && strlen($var) > 0)...
    if(isset($var) && intval($var) > 0)...
    if(isset($var) && $var === '0')...
    

    This seems more verbose, but shows clearly what you're doing. For structural objects it often makes sense to have a shortcut getter, e.g.

     /// get a string
     function s($ary, $key, $default = '') {
         if(!isset($ary[$key])) return $default;
         $s = trim($ary[$key]);
         return strlen($s) ? $s : $default;
     }
     /// get a natural number
     function n($ary, $key, $default = 0) {
         $n = intval(s($ary, $key));
         return $n > 0 ? $n : $default;
     }
    
     $name = s($_POST, 'name');
     $age  = n($_POST, 'age');
    

提交回复
热议问题