logan at logannet dot net
11-Feb-2003 07:42
[[Editors note: Or you can simply use is_numeric()]]
Some people
have offered their ways to find out if a string from a form is an integer
or not, here's my way:
if(ereg("^[0-9]+$",
$_POST["number"])) $_POST["number"] =
(int)$_POST["number"];
In psuedo code:
if you are a
string full of numbers then convert yourself to an integer
So
instead of just checking if its a string full of numbers you check and then
convert it, which means you can use the standard is_int. You can also
do:
if(ereg("^[0-9]+$", $_POST["number"]))
$_POST["number"] += 0;
I think the first way i mentioned
is better because your coding what you want to do, rather than the second
way that uses a side effect of adding 0 to convert the string.
The
first way also may make your code ever so slightly faster (nothing
noticeable) as php does not need to add 0 to the number after it converts
it.
Also note an integer is full numbers (1, 2, 3 etc) not decimal
numbers (1.1, 2.4, 3.7 etc), to convert decimal numbers you could use
something like:
if(ereg("^[.0-9]+$",
$_POST["number"])) $_POST["number"] =
(float)$_POST["number"];
OR
if(ereg("^[.0-9]+$",
$_POST["number"])) $_POST["number"] += 0;
But
note that these would not work with is_int(), because they are not
integers.