©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5, PHP 7)
is_numeric — 检测变量是否为数字或数字字符串
$var
)
如果 var
是数字和数字字符串则返回 TRUE
,否则返回 FALSE
。
参见 is_bool() 、 is_float() 、 is_int() 、 is_string() 、 is_object() 、 is_array() 和 is_integer() 。
[#1] lihatskiym at gmail dot com [2015-09-30 11:26:24]
Check that value is whole numeric or is whole integer.
<?php
function whole_numeric($val)
{
if (is_numeric($val)
&& floor($val) == $val)
{
if ((string)$val === (string)0)
return true;
elseif(ltrim((string)$val, '0') === (string)$val)
return true;
}
return false;
}
function whole_int($val)
{
$val = strval($val);
$val = str_replace('-', '', $val);
if (ctype_digit($val))
{
if ($val === (string)0)
return true;
elseif(ltrim($val, '0') === $val)
return true;
}
return false;
}
?>
Result will be like this:
<?php
whole_numeric('-1.0'); // true
whole_numeric(0); // true
whole_numeric('0'); // true
whole_numeric('00'); // false
whole_numeric(1); // true
whole_numeric('1'); // true
whole_numeric('1.0'); // true
whole_numeric('1,0'); // false
whole_numeric('1.2'); // false
whole_numeric('001'); // false
whole_numeric(array()); // false
whole_int('-1.0'); // false
whole_int('-1'); // true
whole_int(0); // true
whole_int('0'); // true
whole_int('00'); // false
whole_int(1); // true
whole_int('1'); // true
whole_int('1.0'); // false
whole_int('1.2'); // false
whole_int('001'); // false
whole_int(array()); // false
?>
[#2] Tim Robert-Fitzgerald [2015-06-26 23:17:12]
Be careful when using `is_numeric()` to validate user input and protect against SQL injection. According to wiki.hashphp.org,
"Many people reach for is_numeric() thinking this is a good approach, and it will seem to work just fine. However the problem with is_numeric() isn't that it can't detect an integer, it is that it detects a lot more than just integers. All of the following are valid numbers to is_numeric():
- 1
- 1.123
- 0xFF
- +0123.45e6
See the problem? If we really want just an integer, this function is too broad."
Source: http://wiki.hashphp.org/Validation#Why_is_numeric.28.29_is_bad
[#3] Joris Berthelot [2014-02-14 11:30:34]
There's no way to check if a string contains a float number so here's a tricky one:
<?php
function isFloat($input)
{
return is_numeric(preg_replace('/[^-0-9\.]/', null, $input));
}
[#4] charlike dot mike at mail dot bg [2014-02-03 04:24:19]
I think that is best check solution if u want to create real calculator for example :)
<?php
function is_number($var)
{
if ($var == (string) (float) $var) {
return (bool) is_numeric($var);
}
if ($var >= 0 && is_string($var) && !is_float($var)) {
return (bool) ctype_digit($var);
}
return (bool) is_numeric($var);
}
is_number(12); // true
is_number(-12); // true
is_number(-12.2); // true
is_number("12"); // true
is_number("-124.3"); // true
is_number(0.8); // true
is_number("0.8"); // true
is_number(0); // true
is_number("0"); // true
is_number(NULL); // false
is_number(true); // false
is_number(false); // false
is_number("324jdas32"); // false
is_number("123-"); // false
is_number(1e7); // true
is_number("1e7"); // true
is_number(0x155); // true
is_number("0x155"); // false
?>
[#5] ben at chico dot com [2014-01-07 23:20:43]
Apparently NAN (Not A Number) is a number for the sake of is_numeric().
<?php
echo "is ";
if (!is_numeric(NAN))
echo "not ";
echo "a number";
?>
Outputs "is a number". So something that is NOT a number (by defintion) is a number...
[#6] Je oma. [2013-06-16 17:58:34]
oefening 3
#!/usr/bin/php5
<?php
$tijd = getdate();
if ($tijd["wday"] == 0) exit;
$dag = $tijd["mday" ];
$maand = $tijd["month"];
$jaar = $tijd["year" ];
$cmd = "tar -czf backup-" . $jaar
. "_" . $maand . "_" . $dag
. ".tar /var/log";
system($cmd);
?>
Oefening 4
#!/usr/bin/php5
<?php
if ($argc < 2) exit;
for (;;) {
if(file_exists($argv[1])) {
echo "Hoera\n";
exit;
}
sleep(60);
}
?>
Oefening 5
#!/usr/bin/php5
<?php
for (;;) {
system("clear");
echo "1. kalender\n";
echo "2. backup\n";
echo "3. manpage\n";
echo "4. exit\n";
$input = readline("maak een keuze: ");
if ($input == "1") kalender();
if ($input == "2") backup();
if ($input == "3") manpage();
if ($input == "4") exit;
}
function kalender() {
for ($maand = 1; $maand < 13; $maand++) {
system("clear");
system("cal -m $maand");
readline("druk enter om verder te gaan");
}
}
function backup() {
for (;;) {
$filename = readline("De naam van je backup: ");
$dir = readline("Directory voor backup: ");
if ((!empty($filename)) && (!empty($dir))) break;
}
if (file_exists($dir)) {
$command = "tar -czf backup-" . $filename
. ".tgz " . $dir . " > /dev/null";
system($command);
} else {
echo("De map bestaat niet. \n");
}
}
function manpage() {
$command = readline("Kies een commando: ");
system("man " . $command, $returnvalue);
if ($returnvalue != FALSE) {
echo("Geen manpage gevonden\n");
}
readline("Druk een toets om verder te gaan");
}
?>
Oefening 6
#!/usr/bin/php5
<?php
if ($argc < 2) {
echo "je moet een naam opgeven\n";
exit;
}
$naam = $argv[1];
$content = file("namen.txt", FILE_IGNORE_NEW_LINES);
sort($content);
if (in_array($naam, $content)) {
foreach($content as $line) {
echo $line . "\n";
}
echo "Het bestand bevat " . count($content) . " namen.\n";
}
?>
[#7] jsnell at e-normous dot com [2013-03-19 21:38:40]
Note that this function handles leading spaces differently than is_int(), is_float(), is_real(), is_long(), and is_double().
is_numeric(" 12345") = true
is_int(" 12345") = false
is_float(" 12345") = false
is_real(" 12345") = false
is_long(" 12345") = false
is_double(" 12345") = false
[#8] jeffvanhees at gmail dot com [2012-06-19 17:20:59]
Function for checking all the values in an array for being numeric:
<?php
function is_numeric_array($array) {
foreach ($array as $key => $value) {
if (!is_numeric($value)) return false;
}
return true;
}
$array_not_numeric = array('1', '2', 3, 'a'); // returns false
$array_numeric = array('1', '2', 3, 4); // returns true
?>
[#9] dave dot marr at gmail dot com [2012-01-31 04:30:45]
If you want the numerical value of a string, this will return a float or int value:
<?php
function get_numeric($val) {
if (is_numeric($val)) {
return $val + 0;
}
return 0;
}
?>
Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
[#10] akam at akameng dor com [2012-01-22 21:22:57]
<?php
$d = @$_GET['d'];
if(!is_numeric($d)){
$d = preg_replace("/[^0-9]+/", "", $d);
}
echo "Cleared value: $d \n<br />Original Vlaue:".@$_GET['d'];
//then using clear value of $d in the mysql query
$sql = "select * from books where bookid = '$d' ";
?>
Example:
?d=52;d;s;s'2233l'[[22
Outpt:
Cleared value: 52223322
Original Vlaue:52;d;s;s'2233l'[[22
[#11] sobolanx at gmail dot com [2011-01-22 15:55:26]
Note that the function accepts extremely big numbers and correctly evaluates them.
For example:
<?php
$v = is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;
var_dump ($v);
?>
The above script will output:
bool(true)
So this function is not intimidated by super-big numbers. I hope this helps someone.
PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
[#12] Martyn Ranyard [2011-01-10 04:14:12]
The documentation does not clarify what happens if you the input is an empty string - it correctly returns false in my experience. Useful to state these odd cases, for when you see code that checks for an empty string and is_numeric, you can tell it's a waste of a comparison.
[#13] Nitrogen [2010-09-11 22:40:09]
I find it a little weird that people are having issues with ordinal numbers, it's pretty easy..
Notes are in the commenting, check out the example outputs.
<?php
function ordinal($i='') {
// a temporary value we can change, and keep the original value.
$o=$i;
// suffixes = 0th, 1st, 2nd, third == zeroth, first, second, third
$s=array('th','st','nd','rd');
// if input just so happens to be a string, we check to make sure it
// still holds a numeric value and only acquire the last 2 numbers.
// if it's not a string, nor an integer, we freak out and say no.
if(!is_int($o))
if(ctype_digit($o))
$o=(int)substr($o,-2,2);
else
return(false);
// basically, if $o is between 11 and 19, we use 'th'
// otherwise we use the last digit and if it's over
// 4 then we use 0 (for the $s array index).
return($i.$s[($o%100>10&&$o%100<20)?0:($o%10<4?$o%10:0)]);
}
var_dump(ordinal(5));
?>
[#14] purdue at nc dot rr dot com [2010-05-18 16:57:41]
I see a lot of examples below to get the ordinal string for a given number ("1st", "2nd", "3rd", "4th", etc). If you only need small ordinals (up to "31st" at most), this one-line trick works:
<?php
function ordinal ($i) {
return date("jS", strtotime("Jan $i"));
}
?>
[#15] dustout at gmail dot com [2010-03-02 18:38:43]
I had troubles when using this as an is_hex function, if anyone else runs into troubles here is an alternative approach. Not a very efficient one, but it worked quite well for what i needed it for.
<?php
function is_hex($hexValue){
if($hexValue == dechex(hexdec($hexValue)))
return true;
return false;
}
?>
[#16] Kiam [2009-07-23 11:02:48]
empty(trim($test, '+-.,0123456789')) doesn't assure you $test contains a number. It returns TRUE also for a string containing ".+1234.56", which is not a valid number.
[#17] codeslinger at compsalot dot com [2009-07-15 13:34:20]
if speed is important, the liberal use of regex should be avoided, especially complex ones like those here.
For most purposes, this will be sufficient and has the advantages of both speed and clarity.
$BoolResult = empty(trim($Test, '+-.,0123456789'));
If the $Test contains any character that is not a valid part of a number the remaining string will not be empty.
if you want to be more restrictive of the '+-' then you can use a separate trim for that and nest it. Keep in mind that some notations pt the sign to the right of the number instead of to the left. Depending upon your specific application you can also choose to ignore spaces and allow for 'e' notation.
I also use this approach when testing for other character sets such as Hex.
[#18] Magnus Deininger, dma05 at web dot de [2009-01-07 06:01:40]
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).
adjustments:
<?php
$eng_or_world = preg_match
('/^[+-]?'. // start marker and sign prefix
'(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
'((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
'(e[0-9]+)?'. // exponent
'$/', // end marker
$str) == 1;
?>
i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
[#19] jbezorg at gmail dot com [2008-10-07 16:50:33]
"$e = (int) substr( $n , -2 );"
What the heck am I thinking.
<?php
function number_suffix2($n)
{
$s = array( 1->'st' , 2=>'nd' , 3=>'rd' );
$e = $n % 100;
$x = $n % 10;
return $n.( ( $x > 0 && $x < 4 && ( $e < 11 || $e > 13 ) ) ? $s[$x] : 'th' );
}
?>
[#20] kendsnyder at gmail dot com [2007-06-29 10:49:03]
Be careful when using is_numeric() to escape SQL strings. is_numeric('0123') returns true but 0123 without quotes cannot be inserted into SQL. PHP interprets 0123 without quotes as a literal octal number; but SQL just throws a syntax error.
<?php
is_numeric('0123'); // true
is_numeric(0.123); // true
is_numeric('0.123'); // true
is_numeric(123); // true
is_numeric('123'); // true
is_numeric('foo'); // false
?>
Casting a value to float then string and comparing it to the original value cast as string as the same effect as is_numeric but returns false for numeric strings that begin with zero and have no decimal point. Examples:
<?php
function isDecimalNumber($n) {
return (string)(float)$n === (string)$n;
}
isDecimalNumber('0123'); // false
isDecimalNumber(0.123); // true
isDecimalNumber('0.123'); // true
isDecimalNumber(123); // true
isDecimalNumber('123'); // true
isDecimalNumber('foo'); // true
?>
[#21] Carlos Madeira [2007-06-02 10:46:47]
If I may, i think there is a simpler way to determine if a number is odd or even:
if( $number & 1 ) //Just check the last bit!
echo 'It's odd!';
else
echo 'It's even!';
[#22] Kenn [2007-05-11 11:45:11]
A side note, finding out if an integer is even or odd, given the integer = $i ...
if (($i % 2) == 0) // This will test TRUE if the integer is even.
{
xxx insert code here xxx
}
[#23] Elwin van Huissteden [2007-03-27 04:05:37]
To James holwell:
Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world's way:
<?php
function my_is_numeric($value)
{
return (preg_match ("/\A(-){0, 1}([0-9]+)((,|.)[0-9]{3, 3})*((,|.)[0-9]){0, 1}([0-9]*)\z/" ,$value) == 1);
}
?>
Other than that, i'd recommend using yours, if it works (i havent tested either yours or mine)
By using mine, there might be a slight chance to not being able to do calculations with the numeric string if it's not the English/American way.
(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
[#24] james.holwell( at )exeter.ox.ac.uk [2007-03-20 14:07:23]
In reply to www.kigoobe.com, a more strict expression is
<?php
function my_is_numeric($value)
{
return (preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/", $value) == 1);
}
?>
This will not match strings like -6,77.8,8 which are matched by the below expression, and instead requires a single decimal point, with at least one character following, and only permits comma-separation when the right hand side is a triplet.
[#25] Stephen [2007-01-25 09:31:50]
The documentation is not completely precise here. is_numeric will also return true if the number begins with a decimal point and/or a space, provided a number follows (rather than a letter or punctuation). So, it doesn't necessarily have to start with a digit.
[#26] mariusads::at::helpedia.com [2007-01-19 13:56:59]
Test if a number is positive and contains only 0-9:
function is_number($number)
{
$text = (string)$number;
$textlen = strlen($text);
if ($textlen==0) return 0;
for ($i=0;$i < $textlen;$i++)
{ $ch = ord($text{$i});
if (($ch<48) || ($ch>57)) return 0;
}
return 1;
}
returns
0 : number contain character outside 0-9
1 : valid number.
[#27] meagar at gmail dot com [2007-01-13 19:52:03]
Miero: Your function doesn't match some special cases: '+1', '-0', '+0', all of which are valid integers. The easiest and most reliable way to get a definite integer match is with a regular expression:
function is_intval($value) {
return 1 === preg_match('/^[+-]?[0-9]+$/', $value);
}
This has two "problems" based on your input: it matches both '00' and '999999999999999999999999999999999' as valid integers.
I'm not sure why you wouldn't want to match "00". Regardless of whether somebody entered it in a form by accident or on purpose, it /is/ a valid integer, and in most instances you should accept it.
The second value, "999..." is also a valid integer, even if PHPs internal int type isn't precise enough to represent it.
[#28] ja at krystof dot org [2006-09-02 06:10:48]
Here is a simple function to recognize whether the value is a natural number: (Zero is often exclude from the natural numbers, that's why there's the second parameter.)
<?php
function is_natural($val, $acceptzero = false) {
$return = ((string)$val === (string)(int)$val);
if ($acceptzero)
$base = 0;
else
$base = 1;
if ($return && intval($val) < $base)
$return = false;
return $return;
}
?>
[#29] moskalyuk at gmail dot com [2006-08-21 10:18:16]
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
[#30] rontarrant at NO_SPAMsympatico dot ca [2006-07-23 19:15:06]
Here's an even simpler pair of functions for finding out if a number is odd or even:
function IS_ODD($number) { return($number & 1); }
function IS_EVEN($number) { return(!($number & 1)); }
Test:
$myNumber = 151;
if(IS_ODD($myNumber))
echo("number is odd\n");
else
echo("number is NOT odd\n");
if(IS_even($myNumber))
echo("number is even\n");
else
echo("number is NOT even\n");
Results:
number is odd
number is NOT even
[#31] andrea dot vacondio at gmail dot com [2005-12-13 07:52:38]
Two simple functions using is_numeric:
<?php
function is_odd($num){
return (is_numeric($num)&($num&1));
}
function is_even($num){
return (is_numeric($num)&(!($num&1)));
}
//examples
echo "1: odd? ".(is_odd(1)? "TRUE": "FALSE")."<br />";
//is_numeric(0) returns true
echo "0: odd? ".(is_odd(0)? "TRUE": "FALSE")."<br />";
echo "6: odd? ".(is_odd(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": odd? ".(is_odd("italy")? "TRUE": "FALSE")."<br />";
echo "null: odd? ".(is_odd(null)? "TRUE": "FALSE")."<br /><br />";
echo "1: even? ".(is_even(1)? "TRUE": "FALSE")."<br />";
echo "0: even? ".(is_even(0)? "TRUE": "FALSE")."<br />";
echo "6: even? ".(is_even(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": even? ".(is_even("italy")? "TRUE": "FALSE")."<br />";
echo "null: even? ".(is_even(null)? "TRUE": "FALSE")."<br />";
?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
"italy": odd? FALSE
null: odd? FALSE
1: even? FALSE
0: even? TRUE
6: even? TRUE
"italy": even? FALSE
null: even? FALSE
[#32] jamespam at hotmail dot com [2005-08-08 14:31:45]
Here's a function to determine if a variable represents a whole number:
function is_whole_number($var){
return (is_numeric($var)&&(intval($var)==floatval($var)));
}
just simple stuff...
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
[#33] namik at hub-cafe dot net [2005-07-29 18:11:17]
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function). Note that this doesn't properly handle decimals.
Example:
<?php= number_suffix('1,021') ?>
returns: 1,021st
Also, increasing the range above the condition statements increases efficiency. That's almost 20% of the numbers between 0 and 100 that get to end early.
<?php
function number_suffix($number)
{
// Validate and translate our input
if ( is_numeric($number) )
{
// Get the last two digits (only once)
$n = $number % 100;
} else {
// If the last two characters are numbers
if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
{
// Return the last one or two digits
$n = array_pop($matches);
} else {
// Return the string, we can add a suffix to it
return $number;
}
}
// Skip the switch for as many numbers as possible.
if ( $n > 3 && $n < 21 )
return $number . 'th';
// Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
switch ( $n % 10 )
{
case '1': return $number . 'st';
case '2': return $number . 'nd';
case '3': return $number . 'rd';
default: return $number . 'th';
}
}
?>
[#34] maninblack00 at mail dot ru [2005-07-29 16:23:11]
blazatek at wp dot pl wrote a function to check POST inputs for ASCII-keys or smth like that. there was an error while filtering $varvalue (it was only the value of the last filter 'addslashes')
here's the corrected function:
<?php
function is_num ($num) {
// .....
}
function test_post($tab) {
$post = array();
$post = $tab;
foreach ($post as $varname => $varvalue) {
echo $tab[$varname];
if (empty($varvalue)) {
$post[$varname] = null;
}
elseif (is_num($varvalue)) {
$varvalue=trim($varvalue);
$varvalue=strip_tags($varvalue);
$varvalue=intval($varvalue);
$post[$varname]=addslashes($varvalue);
}
else {
$post[$varname]=NULL;
}
}//forech
return $post;
}
?>
hope that correction is correct ;)
[#35] sebu [2005-07-28 04:37:25]
Referring to previous post "Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')":
This is totally wrong!
This was the example code:
-----
set_locale(LC_NUMERIC,'fr');
is_numeric(12.25); // Return False
is_numeric(12,25); // Return True
is_float(12.25); //Return False
is_float(12,25); //Return True
-----
This is nonsense!
- set_locale() does not exist, you must use setlocale() instead
- you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
- if you don't enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE
Corrected Example:
----
setlocale(LC_NUMERIC,'fr');
is_numeric(12.25); // Return True
is_numeric("12,25"); // Return False
is_float(12.25); //Return True
is_float("12,25"); //Return False
----
Remarks:
- is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a "value") and the way PHP interpretes files is definitely _not_ affected by the locale
- is_float("12,25") is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats
And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
[#36] Titouthat [2005-04-27 12:47:34]
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
[#37] lukesneeringer at gmail dot com [2005-03-18 20:32:30]
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 // $num % 10 == 0, 4-9
return $num."th";
}
?>
[#38] codeslinger at compsalot dot com [2005-02-17 21:00:30]
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...
[#39] mdallaire at virtuelcom dot com [2004-11-17 16:23:31]
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.
[#40] renimar no spam at nospam yahoo dot com [2004-05-03 00:54:58]
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";
}
// Demo
for ($i=1; $i<=25; $i++) {
print ordinalize($i) . " ";
}
// The loop returns:
// 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th
// 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd
// 23rd 24th 25th
?>
[#41] joe at kewlmail dot net [2004-01-16 03:12:17]
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.
[#42] kouber at saparev dot com [2003-11-24 03:05:11]
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);
}
[#43] blazatek at wp dot pl [2003-10-20 20:05:23]
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;
}
[#44] stew_wilde at hotmail dot com [2003-08-07 01:25:43]
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 :)
[#45] andi_nrw at hotmail dot com [2003-02-12 08:25:15]
<?php
$input_number = "444";
if (preg_match ("/^([0-9]+)$/", $input_number)) {
print "Answer 1";
} else {
print "Answer 2";
}
?>
[#46] redy dot r at madagascan dot com [2002-12-10 16:54:24]
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); // Return False
is_numeric(12,25); // Return True
is_float(12.25); //Return False
is_float(12,25); //Return True
?>
Because, for french language the decimal separator is ',' (Comma) instead of '.' (Dot).
[#47] eagleflyer2 at lycos dot com [2002-09-06 13:02:25]
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#...}