Count Digits
Write a PHP function that counts the number of digit characters (0-9) in a given string. Return the total count of digits found.
Loop through each character of the string using a for loop and strlen(). Use is_numeric() or ctype_digit() to check if a character is a digit. Increment a counter for each digit found.
Edge cases include empty strings (return 0), strings with no digits (return 0), strings with only digits (return length), and strings with mixed alphanumeric characters.
Counting digits in a string is useful for data validation and parsing. The ctype_digit() function checks if a character is a decimal digit (0-9). Combined with a loop over each character, it provides an accurate digit count.
PHP's ctype_digit() is specifically designed for checking numeric characters and is more reliable than checking ASCII ranges manually. An alternative approach uses preg_match_all('/\d/', $text, $matches) which counts all digits using regex in a single call.
Edge cases include empty strings (return 0), strings with no digits (return 0), and strings where all characters are digits (return string length).
The manual loop approach is educational for understanding character-level string processing, while the regex alternative is more concise for production use.Example Input & Output
Algorithm Flow

Solution Approach
Get the string length with strlen(). Loop with a for loop from 0 to length-1. Access each character with $text[$i]. Use ctype_digit($text[$i]) to check if it is a digit. Increment $count when a digit is found.
Alternative: use preg_match_all('/\d/', $text, $matches) to count all digits at once with regex.
Edge cases: empty string (return 0), no digits (return 0), all digits (return length).
Time O(n), Space O(1).
The for loop with ctype_digit() gives O(n) performance with O(1) space. The regex approach with preg_match_all() is more concise but may be slower for very large strings due to regex compilation overhead.
Best Answers
<?php
function countDigits($text) {
$count = 0;
for ($i = 0; $i < strlen($text); $i++) {
if (ctype_digit($text[$i])) $count++;
}
return $count;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
