/**
* 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
*/