markjaquith / feedback

Ask @markjaquith anything!
42 stars 4 forks source link

empty() vs. ! $var #46

Closed MickeyKay closed 8 years ago

MickeyKay commented 9 years ago

Would love to hear your thoughts on conditional testing for empty/defined variables in PHP. What are your thoughts on best practices, and suggested use cases for the following (and any I'm missing) conditional tests for a specific variable:

Thanks!

bueltge commented 9 years ago

Conditional testing is always usable in the context of the goal. Best practices for me is, use the fastest and exact test for the requirement.

Maybe the table below give you an overview. It give not the one point solution.

Value of variable ($var) isset($var) empty($var) is_null($var)
empty string) bool(true) bool(true)
" " (space) bool(true)
FALSE bool(true) bool(true)
TRUE bool(true)
array() (an empty array) bool(true) bool(true)
NULL bool(true) bool(true)
"0" (0 as a string) bool(true) bool(true)
0 (0 as an integer) bool(true) bool(true)
0.0 (0 as a float) bool(true) bool(true)
var $var; (a variable declared, but without a value) bool(true) bool(true)
NULL byte ("\ 0") bool(true)

Maybe we lost the tables in markdown, below a screenshot: auswahl_002