Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find the sum of a number's digits

Short answer

Turn the number into a string, split it into digits and add them:

<?php
 
echo array_sum(str_split((string) 2026));

Output:

10

Without strings

Take the last digit as the remainder of division by 10:

<?php
 
$number = 2026;
$sum = 0;
 
while ($number > 0) {
    $sum += $number % 10;
    $number = intdiv($number, 10);
}
 
echo $sum;

Output:

10

Functions used in this recipe

  • str_split — Splits a string into pieces of a given length.
  • array_sum — Returns the sum of the values in an array.
  • intdiv — Performs integer division.

Thanks for reading!

Donate to the site — we work hard for you.