function is_nan2($n) {
return $n !== $n;
}
is_nan2(NAN); // true
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
is_nan — 判断是否为合法数值
$val
) : bool
如果 val
为"非数值",例如
acos(1.01)
的结果,则返回 true
。
val
要检查的值
如果 val
不是一个数字(not a number)返回 true
,否则返回 false
。
Example #1 is_nan() 例子
<?php
// Invalid calculation, will return a
// NaN value
$nan = acos(8);
var_dump($nan, is_nan($nan));
?>
以上例程会输出:
float(NAN) bool(true)
function is_nan2($n) {
return $n !== $n;
}
is_nan2(NAN); // true
Starting with PHP 7, the string 'NaN' evaluates to the NaN value as well.
Example:
var_dump( (float) 'NaN' );
PHP 5.x and HHVM:
float(0)
PHP 7.0:
float(NAN)
I would use is_numeric() instead of ctype_digit() if you cannot be 100% sure what data type the string will be. Example from the docs:
<?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 is the * character)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>
I have decided to do some testing because I am getting unusual results with the is_nan function and here are the results of my tests:
<?php
var_dump(NAN); // float NAN
var_dump(NAN == NAN); // boolean true
var_dump(NAN === NAN); // boolean true
var_dump(is_nan(NAN)); // boolean true
var_dump(NAN == 12); // boolean true
var_dump(NAN === 12); // boolean false
var_dump(is_nan(12)); // boolean false
var_dump(NAN == 12.4); // boolean true
var_dump(NAN === 12.4); // boolean true
var_dump(is_nan(12.4)); // boolean false
var_dump(NAN == NULL); // boolean true
var_dump(NAN === NULL); // boolean false
var_dump(is_nan(NULL)); // boolean false
var_dump(NAN == 'K<WNPO'); // boolean true
var_dump(NAN === 'K<WNPO'); // boolean false
var_dump(is_nan('K<WNPO')); // null and throws a warning "Warning: is_nan() expects parameter 1 to be double, string given in NANTest.php on line 13"
It seems odd to me, but in boolean context, NAN evalutes to true.
<?php
var_dump(acos(8));
var_dump((bool)acos(8));
?>
Returns:
float(NAN)
bool(true)
Incidentally INF and -INF also evaluate to true.
For seeing whether or not something is a number, use ctype_digit().
nan/"not a number" is not meant to see if the data type is numeric/textual/etc..
NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.
The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part.
There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.