PHP: Best way to check if input is a valid number?

PHP: Best way to check if input is a valid number?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Trap of Implicit Casting in PHP Number Validation

Validating user input is one of the most common tasks in web development, yet it remains a source of subtle bugs and security vulnerabilities. Your current approach attempts to strip non-numeric characters using (int) casting before checking the string representation. While this logic seems sound on paper, it fails immediately when confronted with edge cases like +111+ or strings containing leading zeros that change type behavior in unexpected ways.

The fundamental issue lies in how PHP handles the cast $num = (int) $val. This operation does not simply "clean" the input; it performs an implicit conversion. When you cast 5xf to an integer, PHP ignores the invalid suffix and returns 5. Your subsequent regex check /^\d+$/ then passes because $num is now just the integer 5, which converts back to the string "5". The validation logic effectively approves garbage input as long as a number can be extracted from it.

You need a strategy that validates the format of the raw input, not the value of the coerced result. For your specific requirements—accepting positive integers like 123 or 012, but rejecting strings with signs like +111+ or alphanumeric mixes—you must inspect the original string $val directly without altering it first.

The Regex Solution for Positive Integers

To strictly enforce that input contains only digits and represents a valid number, a regular expression is the most robust tool. You should validate against the raw input to ensure no hidden characters (like trailing signs or letters) exist.

Here is a corrected approach using preg_match:

$val = trim($input); // Always trim whitespace first

if ($val === '' || $val === '-') {
    return false;
}

// Matches strings containing only digits, including leading zeros like "012"
if (preg_match('/^\d+$/', $val)) {
    return true;
}

return false;

This pattern ^\d+$ asserts that the string starts (^) and ends ($) with one or more digit characters. It explicitly rejects +111+ because the plus sign is not a digit, and it rejects 5xf because of the trailing letter. It also correctly accepts 012 as a valid numeric string, treating the leading zero as part of the format rather than converting it to an octal number automatically.

Why Avoid is_numeric()?

Many developers instinctively reach for is_numeric(). While convenient, this function is often too permissive for strict validation scenarios. is_numeric() will return true for strings like "123.45" (floats), "1e5" (scientific notation), and even "+100".

If your application logic treats all numbers as integers, accepting floats introduces a second step of casting that can reintroduce the very precision errors you are trying to avoid. Furthermore, it fails to distinguish between a string meant to be an integer versus one that merely contains a number. Since your requirements specify rejecting positive signs (+) and floating points, is_numeric() is not a suitable replacement for a strict format check.

Handling the Leading Zero Edge Case

Your source material mentions accepting 012. In standard mathematics, this equals 12. However, in PHP, leading zeros can trigger octal interpretation if you perform arithmetic operations like $val * 1. If $val is "010", multiplying it by 1 results in 8, not 10.

By validating the raw string with regex and returning a boolean, you avoid this pitfall entirely. You are asserting that the input looks like a decimal integer, regardless of how PHP interprets it during arithmetic. If your downstream logic requires treating "012" as the number twelve, simply cast to (int) after validation:

if (preg_match('/^\d+$/', $val)) {
    return true; // Format is valid
}
// Safe to cast now that we know it's clean
$number = (int) $val; 

Conclusion on Input Hygiene

The most reliable way to check if input is a valid number is to validate its string format against the raw data before performing any type coercion. This prevents the "garbage in, garbage out" scenario where partial matches slip through your filters. Always trim whitespace and strictly define what constitutes a valid digit sequence using regex patterns that match your specific constraints.

Our network