Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, can I differentiate the result of intval(null) from intval("0")?

Tags:

php

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
like image 767
Joakim Johansson Avatar asked Oct 12 '12 08:10

Joakim Johansson


1 Answers

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.
}
like image 101
Ja͢ck Avatar answered Nov 01 '22 16:11

Ja͢ck