Open In App
Related Articles

PHP | Sum of digits of a number

Improve Article
Save Article
Like Article

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

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.

// 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);


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 09 Mar, 2018
Like Article
Save Article
Similar Reads
Related Tutorials