PHP program to sum the digits in a number


To sum the digits in a number, the PHP code is as follows −

Example

 Live Demo

<?php
   function sum_of_digits($my_num){
      $sum = 0;
      for ($i = 0; $i < strlen($my_num); $i++){
         $sum += $my_num[$i];
      }
      return $sum;
   }
   $my_num = "65";
   print_r("The sum of digits is ");
   echo sum_of_digits($my_num);
?>

Output

The sum of digits is 11

Above, a function named ‘sum_of_digits’ is defined, that takes an integer as a parameter.

$my_num = "65";

It first declares the variable sum as 0 and then iterates through the length of the declared integer, and adds the element at the ‘i’th place to the sum. Once the iteration is complete, this function returns the sum as output. Outside the function, the value is declared and the function is called by passing this element as the parameter −

function sum_of_digits($my_num){
   $sum = 0;
   for ($i = 0; $i < strlen($my_num); $i++){
      $sum += $my_num[$i];
   }
   return $sum;
}

Updated on: 17-Aug-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements