Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get int instead string from form?

Tags:

Getting variable from form:

<form method = 'POST' action = ''>         <input type = 'text' name = 'a' size = '1' >         <input type = 'submit' value = 'Find it'> </form>" 

If I enter 1 and use gettype($POST_['a']) it returns me string, is it possible to enter int? because after this I want check if that variable is int.

UPDATE

Got answers that it returns always string and they offered me to use (int) or intval(), but then if it's really string like 'a' it returns 0, but it may be also integer value 0, how to overcome this problem?

UPDATE

After editing typo Brad Christie suggested best way, using is_numeric

like image 936
Templar Avatar asked Feb 19 '11 19:02

Templar


People also ask

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

Can we convert string to int in Java?

We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.

How do you convert a string to an int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


2 Answers

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

like image 69
Brad Christie Avatar answered Oct 09 '22 13:10

Brad Christie


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

like image 35
jpsimons Avatar answered Oct 09 '22 13:10

jpsimons