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

Mary-Kate Olsen
Release: 2024-10-26 09:28:02
Original
614 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!