Home  >  Article  >  Backend Development  >  How to Calculate the Sum of Digits in a Numeric String in PHP?

How to Calculate the Sum of Digits in a Numeric String in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 09:28:02615browse

How to Calculate the Sum of Digits in a Numeric String in PHP?

Getting the Sum of Digits in a Numeric String in PHP

PHP offers convenient methods for manipulating numeric strings and retrieving their digit sums.

Question:

How can we determine the sum of all digits in a numeric string in PHP?

Answer:

PHP provides a straightforward way to achieve this task using the array_sum() and str_split() functions. Here's an example:

<code class="php">$number = '12345'; // Numeric string

$digits = str_split($number); // Convert to an array of digits
$sum = array_sum($digits); // Get the sum of digits

echo "Sum of digits: $sum"; // Display the result</code>

This method assumes that the number is positive (or that the conversion of $number to a string generates only digits). If the number contains non-digit characters, the outcome may be inaccurate.

The above is the detailed content of How to Calculate the Sum of Digits in a Numeric String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn