In PHP, it is a common requirement to verify that user input is a valid number. Especially when processing form submissions, it is very important to make sure what the user enters is a number. PHP provides two useful functions: is_numeric() and is_nan() to help us verify input data.
is_numeric() is a PHP built-in function to check if a variable is a numeric or a string of numeric characters. The function returns true if the variable is a numeric or a numeric string, and false if the variable is not a numeric string.
<?php
$var = "123.45";
if (is_numeric($var)) {
echo "$var It is a valid number";
} else {
echo "$var 不It is a valid number";
}
?>
The above code will output 123.45 as a valid number , because the string "123.45" is considered a valid number.
is_nan() is a function used to check whether a variable is of type "Not a Number". Usually, is_nan() is used to verify that the numerical calculation returns an invalid number, such as the result of dividing by zero. It is worth noting that is_nan() can only act on numeric types, so for strings or other types, is_nan() will return false .
<?php
$var = acos(8); // acosThe parameter range of the function is-1arrive1,Out of range will returnNaN
if (is_nan($var)) {
echo "turn outNaN";
} else {
echo "结果It is a valid number";
}
?>
In this example, since the result of acos(8) is NaN, the output will be NaN .
In actual development, users may enter various illegal data, such as empty strings, letters, special characters, etc. To ensure that the input is valid, we can use is_numeric() to determine whether the input is a number, and use is_nan() to ensure that the input does not become an invalid number (NaN). If the user inputs a number and is not calculated as NaN, we can think that the input is a valid number.
<?php
// Get user input
$userInput = $_POST['user_input']; // Assume that the data entered by the user passesPOSTMethod Submit
// Determine whether the input is a valid number
if (is_numeric($userInput) && !is_nan($userInput)) {
echo "输入It is a valid number";
} else {
echo "Invalid input,Please provide a valid number";
}
?>
In this example, first use is_numeric() to determine whether the input is a number. If it is a number, then use is_nan() to check whether the input is a valid number. This ensures that the input is both a number and is not an invalid "NaN" value.
In PHP, is_numeric() and is_nan() are two very useful functions. is_numeric() helps us verify that the input is a valid number, while is_nan() ensures that the number we process is not an invalid NaN value. By combining these two functions, users' input can be more fully verified and invalid data can be avoided.