|
|
 |
is_numeric (PHP 4, PHP 5) is_numeric --
Finds whether a variable is a number or a numeric string
Descriptionbool is_numeric ( mixed var )
Finds whether the given variable is numeric.
Parameters
- var
The variable being evaluated.
Return Values
Returns TRUE if var is a number or a numeric
string, FALSE otherwise.
User Contributed Notes
is_numeric
Gregory Boshoff
14-May-2005 05:01
As mentioned above use the ctype character type functions to determine a strings type as ctype is faster. ctype_digit has far better benchmarks than is_numeric.
// Example:
$num = '888';
if(ctype_digit($num) === TRUE):
echo 'The string variable $num contains the decimal value '.$num;
endif;
pmorgan at ukds dot net
04-May-2005 06:44
Titouthat
27-Apr-2005 02:47
This function converts an input string into bool, int or float depending on its content.
<?php
function convert_type( $var )
{
if( is_numeric( $var ) )
{
if( (float)$var != (int)$var )
{
return (float)$var;
}
else
{
return (int)$var;
}
}
if( $var == "true" ) return true;
if( $var == "false" ) return false;
return $var;
}
?>
'90' return an int
'90.9' return a float
'true' return a bool
'90.0' return a int
lukesneeringer at gmail dot com
18-Mar-2005 10:32
Regarding renimar at yahoo's function to yield ordinal numbers, the function lacks one thing. It accounts for numbers in the teens only if the number is below 100. If you used this function and gave 212 as the input, it would give 212nd, and not 212th. (Also, checking for numbers between 11 and 13 is sufficient, since 14-19 yield th either way.)
Therefore,
<?php if ($num >= 11 and $num <= 19) ?>
should be changed to...
<?php if ($num % 100>= 11 and $num % 100 <= 13) ?>
It will then work perfectly all the time.
Here's the entire function with the one line changed:
<?php
function ordinalize($num) {
if (!is_numeric($num))
return $num;
if ($num % 100 >= 11 and $num % 100 <= 13)
return $num."th";
elseif ( $num % 10 == 1 )
return $num."st";
elseif ( $num % 10 == 2 )
return $num."nd";
elseif ( $num % 10 == 3 )
return $num."rd";
else return $num."th";
}
?>
codeslinger at compsalot dot com
17-Feb-2005 11:00
in version 4.3.10 I find the following
".73" TRUE
"0.73" TRUE
"+0.73" TRUE
"+.73" FALSE
I would not call it a bug, just something to be aware of.
-----
Also be aware that if you give php a huge number and then you convert it to a string you get
"INF"
if you pass that to mySQL etc. you could have a problem...
kiss dot pal at expert-net dot hu
05-Jan-2005 02:13
function is_float_ex($pNum) {
$num_chars=("0123456789.,+-");
if (strlen(trim($pNum))==0) // empty $pNum -> null
return FALSE;
else {
$i=0;
$f=1; // modify
$v=strlen($num_chars)-$f;
while (($i<strlen($pNum)) && ($v>=0)) {
$v=strlen($num_chars)-$f;
while (($v>=0) && ($num_chars[$v]<>$pNum[$i]))
$v--;
if ($f==1) // Only first item + vagy -
$f=3;
if (($pNum[$i]=='.') ||
($pNum[$i]==','))
$f=5;
$i++;
}
if ($v<0)
return FALSE;
else
return TRUE;
}
}
drew at zitnay dot com
04-Jan-2005 08:07
What php at thefriedmans dot net said below about .5 returning false and .0.5 returning true isn't true, at least not for me on PHP 5.0.0. The program:
<?php
echo (is_numeric('5') ? "true" : "false") . "\n";
echo (is_numeric('5.5') ? "true" : "false") . "\n";
echo (is_numeric('.5') ? "true" : "false") . "\n";
echo (is_numeric('.0.5') ? "true" : "false") . "\n";
?>
yields:
true
true
true
false
Just as I would expect.
Drew
admin at carichat dot net
25-Nov-2004 07:09
This Post Responds To mdallaire at virtuelcom dot com.
If You Want To Check To See If A Variable Has Not Letters, PHP Has A Beautiful Built-In Feature Which Allows You To Do So:
<?php
$myString = "0123456789z";
if(ctype_digit($myString))
{
echo "The String $myString Contains Only Numeric Chars.";
}
else
{
echo "The String $myString Does Not Contain Only Numeric Chars.";
}
?>
The Full ctype Listing:
ctype_alnum
ctype_alpha
ctype_cntrl
ctype_digit
ctype_graph
ctype_lower
ctype_print
ctype_punct
ctype_space
ctype_upper
ctype_xdigit
mdallaire at virtuelcom dot com
17-Nov-2004 06:23
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:
function new_is_unsigned_float($val) {
$val=str_replace(" ","",trim($val));
return eregi("^([0-9])+([\.|,]([0-9])*)?$",$val);
}
function new_is_unsigned_integer($val) {
$val=str_replace(" ","",trim($val));
return eregi("^([0-9])+$",$val);
}
function new_is_signed_float($val) {
$val=str_replace(" ","",trim($val));
return eregi("^-?([0-9])+([\.|,]([0-9])*)?$",$val);
}
function new_is_signed_integer($val) {
$val=str_replace(" ","",trim($val));
return eregi("^-?([0-9])+$",$val);
}
It returns 1 if okay and returns nothing "" if it's bad number formating.
php at thefriedmans dot net
13-Oct-2004 12:19
is_numeric() in php5 returns false for strings with a leading decimal point:
<?php
is_numeric('5'); is_numeric('5.5'); is_numeric('.5'); is_numeric('.0.5'); ?>
In certain situations, it may be useful to prepend a '0' to the string you're verifying with is_numeric():
<?php
if (is_numeric('0' . $user_input)) ?>
renimar no spam at nospam yahoo dot com
03-May-2004 02:54
A little function to ordinalize numbers using is_numeric() and accounting for the numbers in the teens.
<?php
function ordinalize($num) {
if (!is_numeric($num))
return $num;
if ($num >= 11 and $num <= 19)
return $num."th";
elseif ( $num % 10 == 1 )
return $num."st";
elseif ( $num % 10 == 2 )
return $num."nd";
elseif ( $num % 10 == 3 )
return $num."rd";
else
return $num."th";
}
for ($i=1; $i<=25; $i++) {
print ordinalize($i) . " ";
}
?>
joe at kewlmail dot net
16-Jan-2004 05:12
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:
$userString = "$654.4r5";
function numpass_filter($userString){
$money = explode(".", $userString);
//now $money[0] = "$645" and $money[1] = "4r5"
//next remove all characters save 0 though 9
//in both elements of the array
$dollars = eregi_replace("[^0-9]", null, $money[0]);
$cents = eregi_replace("[^0-9]", null, $money[1]);
//if there was a decimal in the original string, put it back
if((string)$cents!=null){
$cents = "." . $cents;
}
$result = $dollars . $cents;
return($result);
}
The output in this case would be '654.45'.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
kouber at saparev dot com
24-Nov-2003 05:05
Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.
However, this behaviour is platform-specific.
http://www.php.net/manual/en/language.types.float.php
In such a case, it is suitable to use regular expressions:
function is_numeric_big($s=0) {
return preg_match('/^-?\d+$/', $s);
}
blazatek at wp dot pl
20-Oct-2003 10:05
the best way to check whether
variable is numeric is to check its ascii code :)
function is_num($var)
{
for ($i=0;$i<strlen($var);$i++)
{
$ascii_code=ord($var[$i]);
if ($ascii_code >=49 && $asci_code <=57)
continue;
else
return false;
}
return true;
}
this function can be usefull if you wont to chec eg $_POST
function test_post($tab)
{
$post = array();
$post=$tab;
echo $tab["user_name"];
foreach ($post as $varname => $varvalue)
{
if (empty($varvalue))
{
$post[$varname] = null;
}elseif (is_num($varvalue))
{
$post[$varname]=trim($varvalue);
$post[$varname]=strip_tags($varvalue);
$post[$varname]=intval($varvalue);
$post[$varname]=addslashes($varvalue);
}else
{
$post[$varname]=NULL;
}
}
}//forech
return $post;
}
stew_wilde at hotmail dot com
07-Aug-2003 03:25
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.
ie : two scripts test.php:
<?php
$val = trim($argv[1]);
echo is_string($val);
?>
and testwrapper.php:
<?php
$tmp = 5;
exec("php ./test.php ".$tmp);
?>
Executing testwrapper.php on the command line will echo nothing (ie false), and false will be returned regardless of any escaping of parameters or other such attempts to overcome this. The solution then is to explicitly cast $val in test.php to be an int and then is_numeric will work. But as stated the same test was performed using a string for $val and the is_string() function and the same thing occurs. Not the end of the world, but something to be aware of :)
guidoz at guidoz dot it
07-Jul-2003 12:06
To verify if a char is an alphabetical char (and not a symbol) not do this:
//wrong because also a non alphabetical sympbol will pass the test
if(!is_numeric($char))
but try this...
function is_alphabetical($char)
{
$alphabetical = 'abcdefghijklmopqrstuvwxyz';
if(in_array($char,$alphabetical))
return true;
else
return false;
}
sorry for my ebglish.. I hope you'll undestand
andi_nrw at hotmail dot com
12-Feb-2003 10:25
<?php
$input_number = "444";
if (preg_match ("/^([0-9]+)$/", $input_number)) {
print "Answer 1";
} else {
print "Answer 2";
}
?>
php dot net at davidmcarthur dot com
17-Jan-2003 02:02
This is a little more explicit and won't break when the value can't be legally cast as an int
function is_intValued($var)
{
// Determines if a variable's value is an integer regardless of type
// meant to be an analogy to PHP's is_numeric()
if (is_int($var)) return TRUE;
if (is_string($var) and $var === (string)(int) $var) return TRUE;
if (is_float($var) and $var === (float)(int) $var) return TRUE;
else return FALSE;
}
redy dot r at madagascan dot com
10-Dec-2002 06:54
Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')
Example :
If at the beginning of your script, you declare :
<?php
set_locale(LC_NUMERIC,'fr');
?>
and after, you will get this :
<?php
is_numeric(12.25); is_numeric(12,25); is_float(12.25); is_float(12,25); ?>
Because, for french language the decimal separator is ',' (Comma) instead of '.' (Dot).
martijnt at dataserve dot nl
02-Dec-2002 07:21
If you want to make sure that a variable contains only one or more numbers as in the range 0-9, you could use this:
eregi("[^0-9]",$var)
This checks your variable for anything that is NOT in the range 0-9.
If you use is_numeric() while checking an IP address, you should not be surprised if the following is accepted as a valid IP: 1e13.3.4.12e3 -> is_numeric() considers 1e13 and 12e3 as valid numeric values (which is correct).
Have fun.
Martijn Tigchelaar,
DataServe.
webmaster AT randomportal DOT com
09-Sep-2002 07:46
This is going off on a tangent slightly but as it has been mentioned before I thought it might be an idea to add this, this is the function I use to verify the validity of IP address (takes only one input, the IP address string)
function ip_check($ip)
{
$ip_array = explode(".", $ip);
if (count($ip_array) <> 4)
{
$error = true;
}
for ($loop = 0; $loop < 4; $loop++)
{
if (is_numeric($ip_array[$loop]) != true)
{
$error = true;
}
if (strlen($ip_array[$loop]) > 3)
{
$error = true;
}
if ($ip_array[$loop] > 254)
{
$error = true;
}
if (($loop == 0) OR ($loop == 3))
{
if ($ip_array[$loop] < 1)
{
$error = true;
}
}
else
{
if ($ip_array[$loop] < 0)
{
$error = true;
}
}
}
There are probably a 101 other ways of doing this, but this one has worked for me
eagleflyer2 at lycos dot com
06-Sep-2002 03:02
Hi !
Many of you may have experienced that the 'is_numeric' function seems to fail always when form entries are checked against their variable type. So the function seems to return 'false' even if the form entry was aparently a number or numeric string.
The solution is pretty simple and no subroutines or fancy operations are necessary to make the 'is_numeric' function usable for form entry checks:
Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.
Just use the 'trim' function before 'is_numeric'.
Example:
$variable = trim($variable);
if (is_numeric($variable)
{...#do something#...}
else
{...#do something else#...}
jemore_remove_nospam at nospam dot m6net dot fr
03-Jul-2002 08:17
Note that is_numeric('0xFF') return true.
Note also that echo '0xFF'+0 will return 255, and the hex string has been converted to an int.
stefan at caupo dot de
28-May-2002 01:12
This will return true or false in unpredictable manner:
---------------------------------
$val = "0.0";
echo is_numeric($val);
---------------------------------
purecynergy at hotmail dot com
22-Mar-2002 04:31
I made this function to check IP's so not to get the a.b.c format warning in the gethostbyaddr() function PHP4.
It's basic but solved the is_numeric() multi-[.] problem.
<?php
function is_ip($ip) {
$valid = true;
$ip = explode(".", $ip);
foreach($ip as $block) {
if(!is_numeric($block)) {
$valid = false;
}
}
return $valid;
}
?>
returns true if the string does not contain anything outside the is_numeric() restraints else returns false.
NOTE: this does't validate for full ip's only for the elements. That could be added easily however.
ENJOY!
mjbraca at NOSPAM dot hotmail dot com
24-Oct-2001 12:36
Some examples. Note that leading white space is OK, but not trailing white space, and there can't be white space between the "-" and the number.
is_numeric("1,000") = F
is_numeric("1e2") = T
is_numeric("-1e-2") = T
is_numeric("1e2.3") = F
is_numeric("1.") = T
is_numeric("1.2") = T
is_numeric("1.2.3") = F
is_numeric("-1") = T
is_numeric("- 1") = F
is_numeric("--1") = F
is_numeric("1-") = F
is_numeric("1A") = F
is_numeric(" 1") = T
is_numeric("1 ") = F
tvali at email dot ee
10-Oct-2001 02:53
I changed function sent by
"ealma@hotmail.com 18-May-2001 12:02"
a little bit (it should be faster now).
Here is some code that will detect large values for numeric and for PHP3.
function is_num($s) {
for ($i=0; $i<strlen($s); $i++) {
if (($s[$i]<'0') or ($s[$i]>'9')) {return false;}
}
return true;
}
You can also check only the first char in string (($s[0])<'9')and($s[0]>'0')), since php converts string to numeric only from beginning to the last digit.
aulbach at unter dot franken dot de
17-Sep-2001 01:07
If you want to check, if a string will be converted into the exactly same number, you have to test the following:
if ( (string)(int)$val === (string)$val ) ...
This is not the same as
if ( is_numeric($val) ) ...
cause
<?php
$a="0000001";
if ( is_numeric($a) ) echo "a is numeric";
if ( (string)(float)$a !== (string)$a) echo "a cannot be converted 100%-correctly";
?>
will output:
a is numeric
a cannot be converted 100%-correctly
Ok, ok, I know. This is a hysteric type-check. It depends on the type of application, if you use it. The aim should always be, that the user could be warned, if the value cannot be stored in the way, the user types it into.
Why? Therefore is the following example:
If you set
$a="1E+17";
the above script says that it is all right.
But then we want to convert to INT, not FLOAT. is_numeric() doesn't distinct between INT and FLOAT, so a is_numeric('1E+17') is true, but the Integer of it returns 1, which isn't perhaps, what the user expects.
mark at peak-comm dot com
31-Aug-2001 05:39
This works for PHP3
function is_numeric($n) {
if (ereg("^[0-9]{1,50}.?[0-9]{0,50}$", $n)) {
return(1);
} else {
return(0);
}
}
uioreanu at hotmail dot com
31-Jul-2001 08:55
Or something like:
if (((int) $sWord)== $sWord) {
// numeric only word
// ...
}
php at starnet dot com
19-Jun-2001 06:30
In PHP3, how about this?
function is_numeric($n) {
return(0 + $n == $n);
}
02-Apr-2001 12:20
Seems that this function can only verify numbers up to 16 digits long. Eg:
1111111111111111111
A 19-digit number will return false.
zak at php dot net
19-Nov-2000 06:13
If you are testing a string with is_numeric(), the string must not contain *any* non-numeric data. If it does, is_numeric() will return false.
For example:
is_numeric ("1.21E-100"); // Returns true
is_numeric ("19 Nov 00"); // Returns false
| |