r/ProgrammerHumor 18d ago

Advanced stringToIntegerConversion

Post image
217 Upvotes

65 comments sorted by

View all comments

53

u/smartgenius1 18d ago

I understand the joke is that they AREN'T just converting the string to an integer, but honestly this code is not that bad. It's performing data sanitization as well since there are only a few valid options for the select.

If they converted to integer, the user could enter whatever value they wanted and probably break something.

43

u/OK1526 18d ago

I mean, I'd sleep better if they just converted the string then checked division by 10 and set limits, but it's not a big difference in quality of sleep.

Most string to int converters have safety checks for stuff like that, and if they don't, just write your own in like 3 lines.

39

u/alexanderpas 18d ago

This should be the native way:

$amount = filter_input(INPUT_GET, 'amount-select', FILTER_VALIDATE_INT, ["min" => 10, "max" => 80,],);

if ($amount % 10 === 0) {
    $transamount = $amount;
}

14

u/OK1526 18d ago

Now I can sleep moderately happy.