首頁  >  文章  >  後端開發  >  如何在 PHP 中計算數字字串中的數字總和?

如何在 PHP 中計算數字字串中的數字總和?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-26 09:28:02615瀏覽

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

在PHP 中獲取數字字串中的數字總和

PHP 提供了方便的方法來操作數字字串並檢索其數字字串總和。 🎜>

問題:

如何在 PHP 中確定數字字串中所有數字的總和?

答案:

PHP 提供了一種使用 array_sum() 和 str_split() 函數來完成此任務的簡單方法。以下是範例:

<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>
此方法假設數字為正數(或 $number 到字串的轉換僅產生數字)。如果號碼包含非數字字符,結果可能不準確。

以上是如何在 PHP 中計算數字字串中的數字總和?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn