How to get int instead string from form?

// convert the $_POST['a'] to integer if it's valid, or default to 0
$int = (is_numeric($_POST['a']) ? (int)$_POST['a'] : 0);

You can use is_numeric to check, and php allows casting to integer type, too.

For actual comparisons, you can perform is_int.

Update

Version 5.2 has filter_input which may be a bit more robust for this data type (and others):

$int = filter_input(INPUT_POST, 'a', FILTER_VALIDATE_INT);

I chose FILTER_VALIDATE_INT, but there is also FILTER_SANITIZE_NUMBER_INT and a lot more–it just depends what you want to do.

Leave a Comment