PHP: a short cut for isset and !empty?

后端 未结 11 2089
余生分开走
余生分开走 2021-02-09 13:45

I wonder if there any better ideas to solve the problem below,

I have a form with a number of input fields, such as,



        
11条回答
  •  难免孤独
    2021-02-09 14:09

    This function check if variable is set, is not empty, eventually if has any value.

    /**
     * @param  var - testing variable
     * @param  value
     * @return boolean
     */
    function is(&$var, $value = null){
      if(!is_null($value)){ return IsSet($var) && $var == $value; }
      return IsSet($var) && !empty($var);
    }
    
    echo $_GET['id'];             // this produce Warning
    echo is($_GET['id'])?'1':'0'; // return false
    echo $_GET['id'];             // after first using function is(), will not be produce Warning!!!
    
    is($_GET['id']);              // return false
    IsSet($_GET['id']);           // return false
    $_GET['id'] = 7;
    is($_GET['id'], 7);           // return true;
    

提交回复
热议问题