This sounds to strange to me:
$test_1 = 'string';
$test_2 = '0';
var_dump(intval($test_1)); // Output: int 0
var_dump(intval($test_2)); // Output: int 0
$can_cast = intval($test_2) ? 'sure' : 'nope'; // Wrong!!!
So with a string to int conversion intval returns 0. Fine, but it returns 0 also when the string actually can be casted to zero (because is zero) thus valid.
How can one can distinguish between both (allows ‘0’ as string and deny ‘string’)?
EDIT: ok let me say i know i can use is_numeric. But is_numeric('2.3') returns true, so it can’t help. And:
$test = '0';
var_dump(is_numeric($test) && intval($test)); // Fail!!!
You could do a
ctype_digitcheck before you cast (if you want only positive numbers). Alternatively you could do an integer validation usingfilter_varandFILTER_VALIDATE_INT. The integer validation will also check integer semantics, i.e. it will ensure that the integer is within the allowed range. You can also customize it for your needs through several options.