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

后端 未结 6 591
暗喜
暗喜 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 20:56

    No it's not always true. When you do if($foo) PHP casts the variable to Boolean. An empty string, a Zero integer or an empty array will then be false. Sometimes this can be an issue.

    You should always try to use the most specific comparison as possible, if you're expecting a string which could be empty use if($foo==='') (note the three equal signs). If you're expecting either (boolean) false or a resource (from a DB query for instance) use if($foo===false){...} else {...}

提交回复
热议问题