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!