note 119140 added to function.is-numeric
| From: | VasiliyMakogon | Date: | Fri, 08 Apr 2016 20:22:45 +0000 |
| Subject: | note 119140 added to function.is-numeric | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205187@lists.php.net to get a copy of this message | ||
If you want detect integer of float values, which presents as pure int or float, and presents as
string values, use this functions:
<?php
function isInteger($val)
{
if (!is_scalar($val) || is_bool($val)) {
return false;
}
if (is_float($val + 0) && ($val + 0) > PHP_INT_MAX) {
return false;
}
return is_float($val) ? false : preg_match('~^((?:\+|-)?[0-9]+)$~', $val);
}
function isFloat($val)
{
if (!is_scalar($val)) {
return false;
}
return is_float($val + 0);
}
foreach ([
'11111111111111111', 11111111111111111, // > PHP_INT_MAX - presents in PHP as float
1, '10', '+1', '1.1', 1.1, .2, 2., '.2', '2.',
'-2.', '-.2', null, [], true, false, 'string'
] as $value) {
echo $value . ':' . gettype($value) . ' is Integer? - ' .
(isInteger($value) ? 'yes' : 'no') . PHP_EOL;
echo $value . ':' . gettype($value) . ' is Float? - ' . (isFloat($value) ?
'yes' : 'no') . PHP_EOL;
}
?>
Output:
11111111111111111:string is Integer? - no
11111111111111111:string is Float? - yes
1,1111111111111E+16:double is Integer? - no
1,1111111111111E+16:double is Float? - yes
1:integer is Integer? - yes
1:integer is Float? - no
10:string is Integer? - yes
10:string is Float? - no
+1:string is Integer? - yes
+1:string is Float? - no
1.1:string is Integer? - no
1.1:string is Float? - yes
1,1:double is Integer? - no
1,1:double is Float? - yes
0,2:double is Integer? - no
0,2:double is Float? - yes
2:double is Integer? - no
2:double is Float? - yes
.2:string is Integer? - no
.2:string is Float? - yes
2.:string is Integer? - no
2.:string is Float? - yes
-2.:string is Integer? - no
-2.:string is Float? - yes
-.2:string is Integer? - no
-.2:string is Float? - yes
:NULL is Integer? - no
:NULL is Float? - no
Array:array is Integer? - no
Array:array is Float? - no
1:boolean is Integer? - no
1:boolean is Float? - no
:boolean is Integer? - no
:boolean is Float? - no
string:string is Integer? - no
string:string is Float? - no
----
Server IP: 72.52.91.14
Probable Submitter: 31.185.4.39
----
Manual Page -- http://php.net/manual/en/function.is-numeric.php
Edit -- https://master.php.net/note/edit/119140
Del: integrated -- https://master.php.net/note/delete/119140/integrated
Del: useless -- https://master.php.net/note/delete/119140/useless
Del: bad code -- https://master.php.net/note/delete/119140/bad+code
Del: spam -- https://master.php.net/note/delete/119140/spam
Del: non-english -- https://master.php.net/note/delete/119140/non-english
Del: in docs -- https://master.php.net/note/delete/119140/in+docs
Del: other reasons-- https://master.php.net/note/delete/119140
Reject -- https://master.php.net/note/reject/119140
Search -- https://master.php.net/manage/user-notes.php