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

前端 未结 13 779
自闭症患者
自闭症患者 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:37

    If you want skip empty $filter and dont skip $filter = '0' and others values

    $filter = ''; //or $filter = '0'; or $filter = '1';
    
    //trim the $filter
    
    if( isset($filter) and ( $filter != '' or $filter == '0') ) {
    
    //$filter data 
    
    };
    
    0 讨论(0)
  • 2020-12-06 04:39

    You can't with only empty(). See the manual. You can do this though:

    if ($var !== '0' && empty($var)) {
       echo "$var is empty and is not string '0'";
    }
    

    Basically, empty() does the same as:

    if (!$var) ...
    

    But doesn't trigger a PHP Notice when the variable is not set.

    0 讨论(0)
  • 2020-12-06 04:39
    $var = '0';
    
    // Evaluates to true because $var is empty
    if (empty($var) && $var !== '0') {
        echo '$var is empty or the string "0"';
    }
    
    0 讨论(0)
  • 2020-12-06 04:41

    You can not, because integer,string,float,null does not matter for PHP.

    Because it is cool :)

    You must check characteristic features your variable is_numeric,isset,===,strlen, etc.

    For example:

    if (strlen(@$var)==0) {
        echo @$var . ' is empty';
    }
    

    or

    if (@$var==="" || !isset($var)) {
        echo @$var . ' is empty';
    }
    

    or other examples :)

    thanks for reading.

    0 讨论(0)
  • 2020-12-06 04:41

    if ( (is_array($var) && empty($var)) || strlen($var) === 0 ) { echo $var . ' is empty'; }

    0 讨论(0)
  • 2020-12-06 04:42

    In this case don't use empty, use isset() in place of it. This will also allow 0 as an integer.

    $var = '0';
    if (!isset($var)) {
        print '$var is not set';
    }
    
    $var = 0;
    if (!isset($var)) {
        print '$var is not set';
    }
    

    Neither should print anything.

    0 讨论(0)
提交回复
热议问题