Null OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
Answer from John Green on Stack OverflowNull OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
Use empty(). It checks for both empty strings and null.
if (!empty($_POST['user'])) {
// do stuff
}
From the manual:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
empty, is_null, isset comparisons
Difference between NULL and null in PHP - Stack Overflow
All the ways to handle null values in PHP
Better way to check if values are empty?
What is the difference between null, undefined, and empty in PHP?
- null: A variable is null when it has been explicitly assigned null or has not been assigned any value.โ
- undefined: A variable is considered undefined if it has never been declared or assigned a value. Accessing such a variable will result in a notice-level error.โ
- empty: A variable is considered empty if it holds a falsy value, such as "" (empty string), 0 (integer zero), 0.0 (float zero), "0" (string zero), false, array() (empty array), or null. The empty() function can be used to check for these values.โ
How do I set a variable to null in PHP?
$variable = null;
Alternatively, you can use the unset() function to destroy the variable, which will also set it to null:โ
unset($variable);How can I check if a variable is null in PHP?
$variable = null;
if (is_null($variable)) {
echo "Variable is null";
}
Using strict comparison (===):
$variable = null;
if ($variable === null) {
echo "Variable is null";
}
Using isset() function:
$variable = null;
if (!isset($variable)) {
echo "Variable is null or not set";
}
So I saw this answer on Stackoverflow comparing empty() vs is_null() vs isset():
Is his example at the bottom still the best way in modern PHP?
| โfooโ | โโ | 0 | FALSE | NULL | undefined | |
|---|---|---|---|---|---|---|
empty()
| FALSE | TRUE | TRUE | TRUE | TRUE | TRUE |
is_null()
| FALSE | FALSE | FALSE | FALSE | TRUE | TRUE (ERROR) |
isset()
| TRUE | TRUE | TRUE | TRUE | FALSE | FALSE |
If you want to check if there's any value other than null or undefined, use isset($var)*(because* !is_null() generates a warning on undefined variables.)
If you want to check if the value is non-blank text or any number including zero, it gets trickier:
if (!empty($v) || (isset($v) && ($v === 0 || $v === '0'))) {
// $v is non-blank text, true, 0 or '0'
// $v is NOT an empty string, null, false or undefined
}