How to count the number of digits in an integer with PHP

2 Answers

0 votes
/**
 * Counts digits by converting the number to a string.
 * This approach is clear, safe, and widely used in everyday PHP code.
 */
function countDigitsString(int $value): int
{
    $text = (string)$value;

    // If negative, ignore the leading '-'
    if ($text[0] === '-') {
        return strlen($text) - 1;
    }

    return strlen($text);
}

$number = -12345;
$digits = countDigitsString($number);

echo "Number: $number\n";
echo "Digit count (String method): $digits\n";



/*
run:

Number: -12345
Digit count (String method): 5

*/

 



answered Jul 23, 2021 by avibootz
edited Aug 13 by avibootz
0 votes
/**
 * Counts digits using log10.
 * Uses the formula: floor(log10(n)) + 1
 * Zero is handled separately because log10(0) is undefined.
 */
function countDigitsLog10(int $value): int
{
    $num = abs($value);

    if ($num === 0) {
        return 1;
    }

    return (int)floor(log10($num)) + 1;
}

$number = 987654321;
$digits = countDigitsLog10($number);

echo "Number: $number\n";
echo "Digit count (log10 method): $digits\n";



/*
run:

Number: 987654321
Digit count (log10 method): 9

*/

 



answered Jul 25, 2021 by avibootz
edited Aug 13 by avibootz
...