4 ms·
> defaulting to 0 doesn't count Why this arbitrary restriction? A forced cast of a string to integer is always guaranteed to produce an integer.
by Y-bar 4y ago
> defaulting to 0 doesn't count
Why this arbitrary restriction? A forced cast of a string to integer is always guaranteed to produce an integer.
- dvdkon 4y agoAnd a forced cast is therefore a bad way to generally parse a user-provided string to int.
- samus 4y agoAnd how are we supposed to distinguish that from a legit 0?
- Y-bar 4y agois_numeric() has been available since forever, and is intended for exactly the thing you appear to want to do. https://www.php.net/manual/en/function.is-numeric.php https://www.php.net/manual/en/function.is-numeric.php
- deathanatos 4y agoAt this point you're writing the parser that ships in most language's standard libraries. And, if you naïvely use the suggested function for the purpose you've suggested it for, e.g., like, if(!is_numeric($input)) { error(); } else { return (int)$input; } …you'll parse a lot of strings that still aren't valid integers. (E.g., "2e-2" is "numeric" and would thus parse.)