PHP | Sum of digits of a number

This is a simple PHP program where we need to calculate the sum of all digits of a number.
Examples:

Input : 711 
Output : 9

Input : 14785
Output : 25

In this program, we will try to accept a number in the form of a string and then iterate through the length of the string. While iterating we will extract the digit from each position and then add them to the previously extracted digit, thus getting the sum.



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to calculate the sum of digits
function sum($num) {
    $sum = 0;
    for ($i = 0; $i < strlen($num); $i++){
        $sum += $num[$i];
    }
    return $sum;
}
  
// Driver Code
$num = "711";
echo sum($num);
?>

chevron_right


Output:

9


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.