I have a variable that is definited by a POST call from a form where it is inputed into a text field. Is there any way to convert this variable to an interger?
From the form:
Lenght: <input name="length" value="10" type="text" id="lenght" size="2" />
From the php code:
$length = $_POST['lenght'];
$url = substr($url, 0, $length);
This doesn't seem to work and the only reason why I think it isn't working is because $lenght is defined as text and not an interger.
-
Seems to be a spelling error in your code: length vs. lenght - that could be your problem right there.
To do an explicit conversion, use the intval() function
$length = intval($_POST['length']); -
It likely doesn't work because you misspelled length twice, instead of zero or three times.
Eric Petroelje : I laughed - seen plenty of code like that though. As long as you spell it wrong every time there's no problem right?Michael Myers : Actually, I count three of each spelling, not counting the text of the question.Ilya Birman : Cool explanation :-) -
Two things:
It doesn't work because you misspelled length <-> lenght
The correct way to convert a string to an integer is using the function intval.
$length = intval($_POST['length']); $url = substr($url, 0, $length); -
If you are sure that the value you are looking at has a correct representation for the type you want to convert to, you can also use a vanilla type cast operation:
$int = (int) "1"; // var_dump($int) => int(1) $float = (float) "1.2345"; // var_dump($float) => float(1.2345)Beware of incorrect representations of the variable that you are converting though, i.e casting "a random string" to a number might not yield the results you expect. If you are handling user input, you're better of using the above suggested solutions with function calls such as intval and floatval
-
Ignoring the misspellings of 'length' above, there are a few ways to explicitly convert a string into an integer in PHP. Usually this conversion will happen automatically. Take the following code:
$numeric_string = '42'; echo ($numeric_string * 2);This will print out "84", as expected. See the reference on Type-Juggling.
If you KNOW that the string you have is a number (perhaps by checking is_numeric()) then you can either cast the variable to an Integer
$numeric_string = '42'; $converted_integer = (int) $numeric_string; // or $converted_integer = (integer) $numeric_string;or use intval()
$numeric_string = '42'; $converted_integer = intval($numeric_string);An important point to remember about intval() is that it will return a 0 if it can't resolve the string into an Integer. This could (potentially) give you a second way to check for errors (after is_numeric()), or it could cause unexpected results if you aren't properly insuring that the variable is numeric to begin with.
0 comments:
Post a Comment