In PHP, is_nan() and is_numeric() are two commonly used functions, which are used to determine whether a variable is "not a number" (NaN) and whether it is a number or a numeric string. However, many people may be confused why in some cases is_nan() returns true , is_numeric() may return false . This article will dig into how these two functions work in depth and explain the differences between them.
is_nan() is a function used to check whether a value is NaN (Not a Number). NaN is a special floating point value that represents an illegal numerical calculation result. For example, when you perform some math operations, NaN may be returned if the result is not a valid number. Generally, NaN is caused by the following situations:
0 Divided by 0
Square root of negative number
Invalid mathematical expression (such as: converting invalid strings into numbers)
These illegal numbers can be detected using is_nan() .
$var1 = acos(2); // This is an illegal operation,acos(2) Will return NaN
$var2 = 0 / 0; // 0 Divide by 0 The result is also NaN
echo is_nan($var1); // Output true
echo is_nan($var2); // Output true
is_numeric() is used to determine whether a variable is a numeric string or a numeric string. This function checks whether the given value is a legal numeric type, or whether it can be converted to a number. It should be noted that is_numeric() does not check whether the value is a valid floating point number, but only checks whether it can be represented as a number (including integers or floating point number).
echo is_numeric(123); // Output true,123 It's a number
echo is_numeric("123"); // Output true,String "123" 也It's a number
echo is_numeric("12.34"); // Output true,String "12.34" 也It's a number
echo is_numeric("abc"); // Output false,"abc" 不It's a number
Although both is_nan() and is_numeric() involve detection of numbers, their inspection mechanisms vary, especially when dealing with NaN.
is_nan() is specifically used to check if a value is NaN, which is a special "non-number" value. NaN is a state of floating points, and is_numeric() only cares whether the value can be converted into a valid number.
When is_nan() returns true , is_numeric() returns false because NaN is not a valid number, and is_numeric() can only recognize valid numbers or strings that can be converted into numbers. NaN cannot be considered a legal number, so is_numeric() returns false .
$var = acos(2); // NaN
echo is_nan($var); // Output true,$var yes NaN
echo is_numeric($var); // Output false,NaN 不yes一个合法的数字
is_nan() can only determine whether a value is NaN. When it returns true , it means that the value is an illegal number.
is_numeric() is used to check if a value can be used as a valid number, while NaN is considered an invalid number, so it returns false .
This is why in PHP, is_numeric() returns false when is_nan() returns true .