Page 1 of 1
validating a number
Posted: Mon Jan 09, 2006 7:25 am
by hame22
sorry people but how do i validate a string so i can check that it is an integer?
thanks
I have this at the moment:
Posted: Mon Jan 09, 2006 7:29 am
by s.dot
which can be sometimes misused because sometimes people use it on numbers that start with 0.. which isn't an integer.
In that case, you should use is_numeric()
Posted: Mon Jan 09, 2006 7:48 am
by Jenk
Code: Select all
<?php
if (strval(intval($num)) === $num) {
//$num is a string representation of an int
}
?>
is_int() would fail because the OP wants to test a string, thus not an int.

Posted: Mon Jan 09, 2006 8:24 am
by s.dot
but PHP isn't type strict? "6" is the same as 6? that's what I've come to understand.
but anyways, help me learn here

how do you know the OP is looking for a string?
couldn't $value be an int or a string?
Posted: Mon Jan 09, 2006 8:58 am
by raghavan20
Code: Select all
if (preg_match("/^[0-9]$/", $var))
Posted: Mon Jan 09, 2006 9:16 am
by feyd
don't forget the
ctype functions, and
is_numeric()
Posted: Mon Jan 09, 2006 9:48 am
by Maugrim_The_Reaper
Can only agree with feyd. Relying on a regex to check for a number as string is OTT, unless you require a specific format. Otherwise use the far more scaleable is_numeric(). This will validate any variable type as numeric (though not necessarily an integer!)
ctype_digit() generally accepts only known strings - so be careful you don't use it where the parameter could be a valid integer, or use ctype_digit( (string) $somevar ); to make certain.
If that confused you - use is_numeric(), then cast to integer if that's the number type you expect.