how to get length of integers in PHP ?

how to get length of integers in PHP ?

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

Stefan Bogdanescu

Founder & Senior Architect

The Trap of strlen and How to Properly Validate Integer Lengths in PHP

Developers often stumble when trying to validate numeric fields because they conflate string length with integer value length. A common scenario involves validating mobile numbers or credit card IDs where the requirement is strictly "10 digits." In PHP, if you simply grab a user input like "123-456-7890" and run strlen(), you might get 11. If you strip hyphens first, you get 10. But what if the user enters "123a456789"? The string length is still 10, but it contains a non-numeric character. Relying solely on strlen() without type checking leads to logic errors that bypass your validation rules entirely.

The core issue arises from how PHP handles data types. When you receive input via $_POST or $_GET, it arrives as a string. To validate an integer length, you must first ensure the content is strictly numeric before measuring its size. Attempting to cast this string directly to an integer using (int) truncates everything after the decimal point and stops at the first non-numeric character.

$input = "123abc456";
$intValue = (int)$input; 
// $intValue becomes 123, losing all subsequent data

If you then check the length of this casted integer, you get 1 or 3, not the intended 10. This is why direct casting is dangerous for length validation. Instead, you need to filter the string to remove whitespace and non-numeric characters before counting, or verify that no non-numeric characters exist in the first place.

For strict mobile number validation where alphabetic characters are forbidden, a regular expression combined with a count is the most robust approach. The pattern /^(\d+)$/ ensures the entire string consists only of digits. Once confirmed, you can safely use strlen() to check the digit count against your specific requirement.

function validateMobileNumber(string $mobile): bool {
    // Remove any potential whitespace
    $cleaned = trim($mobile);
    
    // Check if the string contains ONLY digits and has a length of exactly 10
    return preg_match('/^\d{10}$/', $cleaned) === 1;
}

$input = "9876543210";
if (validateMobileNumber($input)) {
    echo "Valid 10-digit mobile number.";
} else {
    echo "Invalid: Must be exactly 10 digits and no letters.";
}

This method avoids the pitfalls of casting. The regex anchor ^ and $ forces the pattern to match the entire string, preventing false positives where a long string happens to start or end with the correct number of digits. If you need to allow formatting like hyphens or spaces (e.g., "123-456-7890"), adjust the regex to /\d{10}/ but ensure you validate that no other characters remain after stripping them, or strictly define the allowed separators in the pattern.

In larger applications, this logic often lives inside a validation layer. If you are using a framework like Laravel, you might be tempted to create a custom validation rule. While possible, it is often cleaner to rely on native rules for simple constraints. However, if your business logic requires complex regex patterns for specific numeric fields, a custom rule class is appropriate.

Consider the trade-off between performance and readability. For high-frequency checks in a loop, a simple ctype_digit() check followed by strlen() is faster than running a full PCRE (Perl Compatible Regular Expressions) engine, though the difference is negligible for single-user inputs. However, ctype_digit() returns false if the string contains non-digit characters, making it an efficient first-pass filter before you even attempt length checks on malformed data.

if (ctype_digit($cleaned)) {
    if (strlen($cleaned) === 10) {
        // Proceed with business logic
    }
}

This two-step approach separates concerns: type checking first, then length validation. It prevents unnecessary regex execution on obviously invalid inputs. Always remember that strlen() operates on bytes in PHP. While this rarely matters for ASCII digits (0-9), it becomes critical when dealing with UTF-8 encoded characters or if your database stores numbers as strings with variable byte lengths. For standard integer validation, assuming single-byte ASCII is safe, but be wary of locales where numeric symbols differ from the standard 0-9 set.

Ultimately, validating integer length is not just about counting characters; it is about ensuring semantic correctness. You are validating that the input represents a specific magnitude of value without corruption. By combining strict type checking with precise length constraints, you build validation logic that is resilient against common user input errors like trailing spaces or accidental letter entry.

Our network