
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP program to sum the digits in a number
To sum the digits in a number, the PHP code is as follows −
Example
<?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; }
- Related Articles
- C++ Program to Sum the digits of a given number
- C Program to sum the digits of a given number in single statement
- Python Program to Find the Sum of Digits in a Number without Recursion
- PHP program to check if all digits of a number divide it
- C# program to find the sum of digits of a number using Recursion
- Write a Golang program to find the sum of digits for a given number
- Program to find the sum of all digits of given number in Python
- Java Program to Find Sum of Digits of a Number using Recursion
- C program to find sum of digits of a five digit number
- Haskell Program to Find Sum of Digits of a Number using Recursion
- C++ program to find sum of digits of a number until sum becomes single digit
- Golang Program to Count the Number of Digits in a Number
- 8085 program to find sum of digits of 8 bit number
- 8086 program to find sum of digits of 8 bit number
- Prime digits sum of a number in JavaScript

Advertisements