If your variable should be a number, do not use empty
. Just read what the documentation says:
Value Returned
Returns FALSE
if var exists and is not empty, and
does not contain a zeroed value. Otherwise it will return TRUE
.
What is seen below is considered empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a floating point)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- $var; (a declared variable but no value)
That is, if the variable is equal to 0, empty
will return true even if a valid number.
If, in any way, the variable can arrive at being set, use the isset
to verify its existence and is_numeric
to check if it is numerical:
isset($number) and is_numeric($number)
But the only situation that I imagine, at the moment, that it is plausible to verify the existence of the variable is when it comes by an HTTP request and in this case the ideal is to do:
$number = filter_input(INPUT_GET, 'number', FILTER_VALIDATE_INT);
Thus, $number
will always be set and will be equal to the value, if the given value was a number, false if the filter fails or null if the variable was not set in $_GET
.
What if
$numer
(sic) is equal to 0?– Woss
True friend. I hadn’t thought of that hypothesis, I’ll add a new condition to the answer.
– user113606