Page 1 of 1

Numeric String

Posted: Fri Oct 20, 2006 4:24 am
by hmsg
Hello!

I have field in a form that is receveing a number, i need to test if is a integer, how do i do that?
If i could use de is_int() function my problem woul be resolved, but i can't because when the value comes by a form is a numeric string, and i only could use the function is_numeric(), but that function doesn't interest me because my number must be a integer and the is_numeric() function acepts decimal numbers.

Is there anyway to test my variable?


With the best regards

Hugo Gomes

Posted: Fri Oct 20, 2006 4:38 am
by volka

Posted: Fri Oct 20, 2006 4:40 am
by CoderGoblin
Cannot understand why is_int shouldn't work but must admit to not using it...

One way of doing it is to check the value against the floor of the value. If they are the same it's an integer.

Code: Select all

if ($value==floor($value)) {
  //Its an integer
}

Posted: Fri Oct 20, 2006 4:46 am
by volka
CoderGoblin wrote:Cannot understand why is_int shouldn't work but must admit to not using it...
because is_int checks the (internal) variable type and http paraemter always ship as strings.

Code: Select all

<?php
function foo(&$bar) {
	echo gettype($bar), "<br />\n";
	echo 'value: ', $bar, "<br />\n";
	echo 'is_int:', is_int($bar) ? 'yes':'no', "<br />\n";
	echo 'is_string:', is_string($bar) ? 'yes':'no', "<br />\n";
	echo "<hr />\n";
}

$i = 1;
$s = '1';

foo($i);
foo($b);
?>

Posted: Fri Oct 20, 2006 11:45 am
by s.dot
Use typecasting..

Code: Select all

$value = (int) $value;

Posted: Fri Oct 20, 2006 2:59 pm
by Cameri
if you just require to check if it is a number, you should do like scottayy said, typecasting, that is.
Now, if you need to check if the number is within a valid range, something logical, lets say there's no reason why an user should input 9999999, if the number should be between 1000 and 3000, then after you typecast, you just check that the number is in that range.

Code: Select all

$myInt = (int)$_POST['myInt'];
if ($myInt >= 1000 && $myInt<=3000) {
 //user posted a valid integer
}

Posted: Fri Oct 20, 2006 3:10 pm
by feyd
Cameri wrote:Now, if you need to check if the number is within a valid range, something logical, lets say there's no reason why an user should input 9999999, if the number should be between 1000 and 3000, then after you typecast, you just check that the number is in that range.
I prefer to simply force it into the range if it's that case.

Code: Select all

$num = min(max((int)$num, $min), $max);