Closed MickeyKay closed 8 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.
empty
— Determine whether a variable is empty! $var
— is the same as $var == FALSE
. Also, one should take into account that type conversion takes place when using ==
operator.is_null
— Finds whether a variable is NULL isset
— Determine if a variable is set and is not NULL 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:
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!