How can one efficiently calculate the sum of digits in a given number using PHP?

To efficiently calculate the sum of digits in a given number using PHP, you can convert the number to a string and then iterate through each digit, converting it back to an integer and summing them up.

<?php
function sumOfDigits($number) {
    $sum = 0;
    $number = (string)$number;
    
    for($i = 0; $i < strlen($number); $i++) {
        $sum += (int)$number[$i];
    }
    
    return $sum;
}

// Example usage
$number = 12345;
echo "The sum of digits in $number is: " . sumOfDigits($number);
?>