Most people use isset to check if a POST variable ( i.e. isset(_POST(‘textfield’)) ) has been entered. However, as the table displays below, if the user enters an empty string ( “”) isset will give an unexpected result.
Instead we should use the following:
|
1 |
array_key_exists('textfield', $_POST) && !empty($_POST['textfield']) |
The combination of array_key_exists and empty will check if the value is not only set but also not an empty string ( “”) or NULL.
| Value of variable ($var) | isset($var) | empty($var) | is_null($var) |
|---|---|---|---|
| “” (an empty string) | bool(true) | bool(true) | bool(false) |
| ” ” (space) | bool(true) | bool(false) | bool(false) |
| FALSE | bool(true) | bool(true) | bool(false) |
| TRUE | bool(true) | bool(false) | bool(false) |
| array() (an empty array) | bool(true) | bool(true) | bool(false) |
| NULL | bool(false) | bool(true) | bool(true) |
| “0” (0 as a string) | bool(true) | bool(true) | bool(false) |
| 0 (0 as an integer) | bool(true) | bool(true) | bool(false) |
| 0.0 (0 as a float) | bool(true) | bool(true) | bool(false) |
| var $var; (a variable declared, but without a value) | bool(false) | bool(true) | bool(true) |
| NULL byte (“\ 0”) | bool(true) | bool(false) | bool(false) |
Table Credit to: @virendrachandak on Twitter