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);
?>
Keywords
Related Questions
- Are there any specific best practices for writing server-side scripts in PHP to handle individual user connections for Websockets?
- What are the best practices for handling loops in PHP when interacting with a database?
- What potential issues can arise when using PHP to filter and display data based on user input such as month selection?