What are common pitfalls when trying to validate numerical values in PHP?

One common pitfall when trying to validate numerical values in PHP is not properly checking for the data type. It's important to ensure that the input is indeed a number and not a string or any other data type. Another pitfall is not handling edge cases, such as negative numbers or decimals, depending on the requirements of the validation. To solve this, you can use PHP's built-in functions like is_numeric() or filter_var() with the FILTER_VALIDATE_FLOAT or FILTER_VALIDATE_INT filter.

// Validate numerical value using is_numeric() function
$number = "42";
if (is_numeric($number)) {
    echo "Valid numerical value";
} else {
    echo "Invalid numerical value";
}

// Validate numerical value using filter_var() function
$number = "3.14";
if (filter_var($number, FILTER_VALIDATE_FLOAT)) {
    echo "Valid numerical value";
} else {
    echo "Invalid numerical value";
}