Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 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.



And a forced cast is therefore a bad way to generally parse a user-provided string to int.


So why do you insist on using it that way?


I don't. I asked for an int parsing function, got (int)$val as a suggestion, so I had to explain why it doesn't fit the bill.


And how are we supposed to distinguish that from a legit 0?


is_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


At 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.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: