How to get int instead string from form?

后端 未结 5 1217
北海茫月
北海茫月 2020-11-28 14:15

Getting variable from form:

相关标签:
5条回答
  • 2020-11-28 14:49

    Sending over the wire via HTTP, everything is a string. It's up to your server to decide that "1" should be 1.

    0 讨论(0)
  • 2020-11-28 14:52

    I'd use (int)$_POST['a'] to convert it to an integer.

    0 讨论(0)
  • 2020-11-28 14:52

    if you prefer mantain a wide type compatibility and preserve input types other than int (double, float, ecc.) i suggest something like this:

    $var = is_numeric($_POST['a'])?$_POST['a']*1:$_POST['a'];
    

    You will get:

    $_POST['a'] = "abc"; // string(3) "abc"
    $_POST['a'] = "10"; // int(10)
    $_POST['a'] = "10.12"; // float(10.12)
    
    0 讨论(0)
  • 2020-11-28 15:02

    No. HTTP only deals with text (or binaries).

    You have to convert it.

    0 讨论(0)
  • 2020-11-28 15:05
    // 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.

    0 讨论(0)
提交回复
热议问题