Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sum of digits in PHP

Tags:

string

php

sum

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

like image 229
Leticia Meyere Avatar asked Jul 12 '10 21:07

Leticia Meyere


People also ask

How do you sum a string in PHP?

String Operators ¶ The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' . = '), which appends the argument on the right side to the argument on the left side.

What is prime number in PHP?

A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7, 11, 13, 17, etc. are prime numbers.


1 Answers

array_sum(str_split($number)); 

This assumes the number is positive (or, more accurately, that the conversion of $number into a string generates only digits).

like image 66
Artefacto Avatar answered Oct 01 '22 03:10

Artefacto