Get the sum of digits in PHP

后端 未结 13 2797
攒了一身酷
攒了一身酷 2020-11-29 10:45

How do I find the sum of all the digits in a number in PHP?

13条回答
  •  被撕碎了的回忆
    2020-11-29 11:43

    Artefactos method is obviously unbeatable, but here an version how one could do it "manually":

    $number = 1234567890;
    $sum = 0;
    do {
        $sum += $number % 10;
    }
    while ($number = (int) $number / 10);
    

    This is actually faster than Artefactos method (at least for 1234567890), because it saves two function calls.

提交回复
热议问题