if($val) vs. if($val != “”) vs. if(!empty($val)) — which one?

后端 未结 6 598
暗喜
暗喜 2020-12-09 20:39

I see a lot of people using a variety of different methods to check whether of a variable is empty, there really seems to be no consensus. I\'ve heard that if($foo)

6条回答
  •  天命终不由人
    2020-12-09 21:09

    You may read the documentation about casting to boolean to find the answer to this question. There's a list in there with which values are converted to true and false, respectively.

    Note that empty also checks if the variable is set, which regular comparison does not. An unset variable will trigger an error of type E_NOTICE during comparison, but not when using empty. You can work around this using the isset call before your comparison, like this:

    if(isset($foo) && $foo != '')
    

提交回复
热议问题