- Сложить все числа в массиве
- PHP array_sum() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- PHP Array Sum
- Use the array_sum() Function to Sum the Values of an Array in PHP
- Calculate the Sum of All Values of a Multidimensional Array in PHP
- Calculate the Sum of a Particular Column of a Multidimensional Array Using sum_array() Function in PHP
- Related Article — PHP Array
- PHP Функция array_sum()
- Синтаксис
- Параметр значений
- Технические подробности
- Еще примеры
- Пример
- ВЫБОР ЦВЕТА
- Сообщить об ошибке
- Ваше предложение:
- Спасибо Вам за то, что помогаете!
Сложить все числа в массиве
Сложить все числа в массиве можно через функцию array_sum() .
$chars = array(1, 2, 3, '4', '5'); array_sum($chars); // 15
Функция array_sum() игнорирует нечисловые значения.
$chars = array(1, 2, 3, 4, 5, 'PHP', false, [1,2,4]); array_sum($chars); // 15
Если чисел в массиве не будет, то функция array_sum() вернёт «0».
$chars = array(); array_sum($chars); // 0
Авторизуйтесь, чтобы добавлять комментарии
PHP array_sum() Function
Return the sum of all the values in the array (5+15+25):
Definition and Usage
The array_sum() function returns the sum of all the values in the array.
Syntax
Parameter Values
Technical Details
Return Value: | Returns the sum of all the values in an array |
---|---|
PHP Version: | 4.0.4+ |
PHP Changelog: | PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which often converted them to zero, depending on their value) |
More Examples
Example
Return the sum of all the values in the array (52.2+13.7+0.9):
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
PHP Array Sum
- Use the array_sum() Function to Sum the Values of an Array in PHP
- Calculate the Sum of All Values of a Multidimensional Array in PHP
- Calculate the Sum of a Particular Column of a Multidimensional Array Using sum_array() Function in PHP
PHP has a built-in function array_sum() , which is used to sum all the values of an array.
This function takes one parameter, the array you want to sum values. It only takes a one-dimensional and associative array as a parameter.
The array_sum() returns an integer or float value after adding all the values; if the array is empty, it will return 0 .
This tutorial demonstrates the uses of array_sum() and how to sum the values of a multidimensional array.
Use the array_sum() Function to Sum the Values of an Array in PHP
The array_sum() can only be used for one-dimensional and associative arrays.
// Sum of the values of a one dimensional array. $sum_array=array(10,20,30,40,50); echo "Sum of the one-dimensional array is: " echo array_sum($sum_array); echo "
"; // Sum of the values of one associative array. $sum_array=array("val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5); echo "Sum of the associative array is: " echo array_sum($sum_array);
The above code will sum the values of the corresponding array. In the case of an associative array, the array_sum() will only sum the values, not the keys.
Sum of the one-dimensional array is: 150 Sum of the associative array is: 152.5
Calculate the Sum of All Values of a Multidimensional Array in PHP
We can use foreach loops for a multidimensional array to calculate the sum of all values.
php $multi_array = [ ["val1"=>10,"val2"=>20,"val3"=>30,"val4"=>40,"val5"=>50], ["val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5], ["val1"=>60,"val2"=>70,"val3"=>80,"val4"=>90,"val5"=>100], ["val1"=>60.5,"val2"=>70.5,"val3"=>80.5,"val4"=>90.5,"val5"=>100.5] ]; $sum_array = array(); foreach ($multi_array as $k=>$sub_array) foreach ($sub_array as $id=>$val) $sum_array[$id]+=$val; > > print "Sum of full Array : ".array_sum($sum_array)."
"; ?>
The code above will first calculate the sum of columns of a multidimensional array and return an array with the sum of columns values. Then we use sum_array() function.
Calculate the Sum of a Particular Column of a Multidimensional Array Using sum_array() Function in PHP
As we know, sum_array() cannot return the sum of a multidimensional array, but it can be used with another built-in function, array_column() .
The array_column() will return an array with keys and values with a column from the given multidimensional array. It takes two mandatory parameters, the array and column or index key.
php $multi_array = [ ["val1"=>10,"val2"=>20,"val3"=>30,"val4"=>40,"val5"=>50], ["val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5], ["val1"=>60,"val2"=>70,"val3"=>80,"val4"=>90,"val5"=>100], ["val1"=>60.5,"val2"=>70.5,"val3"=>80.5,"val4"=>90.5,"val5"=>100.5] ]; $sum_val1 = array_sum(array_column($multi_array, "val1")); print "Sum of column val1 : ".$sum_val1."
"; $sum_val2 = array_sum(array_column($multi_array, "val2")); print "Sum of column val2 : ".$sum_val2."
"; $sum_val3 = array_sum(array_column($multi_array, "val3")); print "Sum of column val3 : ".$sum_val3."
"; $sum_val4 = array_sum(array_column($multi_array, "val4")); print "Sum of column val4 : ".$sum_val4."
"; $sum_val5 = array_sum(array_column($multi_array, "val5")); print "Sum of column val5 : ".$sum_val5."
"; ?>
Sum of column val1 : 141 Sum of column val2 : 181 Sum of column val3 : 221 Sum of column val4 : 261 Sum of column val5 : 301
We can also use loops with array_sum and array_column() functions to calculate the sum of all values of a multidimensional array.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
Related Article — PHP Array
PHP Функция array_sum()
Функция array_sum() возвращает сумму всех значений в массиве.
Синтаксис
Параметр значений
Технические подробности
Возврат значения: | Возвращает сумму всех значений в массиве |
---|---|
PHP Версия: | 4.0.4+ |
PHP Список изменений: | Версии PHP до версии 4.2.1 модифицировали сам передаваемый массив и преобразовывали строки в числа (которые часто преобразовывали их в ноль, в зависимости от их значения) |
Еще примеры
Пример
Возвращает сумму всех значений в массиве (52.2+13.7+0.9):
Мы только что запустили
SchoolsW3 видео
ВЫБОР ЦВЕТА
Сообщить об ошибке
Если вы хотите сообщить об ошибке или внести предложение, не стесняйтесь отправлять на электронное письмо:
Ваше предложение:
Спасибо Вам за то, что помогаете!
Ваше сообщение было отправлено в SchoolsW3.
ТОП Учебники
ТОП Справочники
ТОП Примеры
Получить сертификат
SchoolsW3 оптимизирован для бесплатного обучения, проверки и подготовки знаний. Примеры в редакторе упрощают и улучшают чтение и базовое понимание. Учебники, ссылки, примеры постоянно пересматриваются, чтобы избежать ошибок, но не возможно гарантировать полную правильность всего содержания. Некоторые страницы сайта могут быть не переведены на РУССКИЙ язык, можно отправить страницу как ошибку, так же можете самостоятельно заняться переводом. Используя данный сайт, вы соглашаетесь прочитать и принять Условия к использованию, Cookies и политика конфиденциальности.