note 29346 added to function.is-int
| From: | logan at logannet dot net | Date: | Mon, 10 Feb 2003 21:42:32 +0000 |
| Subject: | note 29346 added to function.is-int | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-43740@lists.php.net to get a copy of this message | ||
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.
--
http://www.php.net/manual/en/function.is-int.php
http://master.php.net/manage/user-notes.php?action=edit+29346
http://master.php.net/manage/user-notes.php?action=delete+29346
http://master.php.net/manage/user-notes.php?action=reject+29346