I get input values via POST, some of them might be ID's referring to other things, and some start at 0. When choosing something with ID 0, or something without a value, is there a method like intval()
that returns something more helpful than 0
on failure to parse? Or can I somehow differentiate the result of intval()
from the failure to parse?
Example:
echo intval(null); // 0
echo intval("0"); // 0
You can use the filter_var()
function to determine the difference:
filter_var(null, FILTER_VALIDATE_INT);
// false
filter_var('0', FILTER_VALIDATE_INT);
// int(0)
You can also add flags to specifically accept hexadecimal and octal values, but I wouldn't recommend that for your case.
Btw, in the more likely case that the variable comes from $_POST
, you can also use filter_input()
:
if (is_int($nr = filter_input(INPUT_POST, 'nr', FILTER_VALIDATE_INT))) {
// $nr contains an integer
}
The reason I'm using is_int()
on the result of filter_input
is because when nothing is posted, null
is returned; using is_int()
guards against this issue.
Edit
If the question is really just about null
vs '0'
you can just compare $var !== null
:
if (!is_null($var)) {
// $var is definitely not null
// but it might also be an object, string, integer, float even, etc.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With