Просуммировать все значения массива php

Сложить все числа в массиве

Сложить все числа в массиве можно через функцию 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 

Авторизуйтесь, чтобы добавлять комментарии

Источник

array_sum

array_sum() возвращает сумму значений массива.

Список параметров

Возвращаемые значения

Возвращает сумму значений в виде целого числа или числа с плавающей точкой; 0 , если array пуст.

Примеры

Пример #1 Пример использования array_sum()

$a = array( 2 , 4 , 6 , 8 );
echo «sum(a) color: #007700″>. array_sum ( $a ) . «\n» ;

$b = array( «a» => 1.2 , «b» => 2.3 , «c» => 3.4 );
echo «sum(b) color: #007700″>. array_sum ( $b ) . «\n» ;
?>

Результат выполнения данного примера:

User Contributed Notes 6 notes

If you want to calculate the sum in multi-dimensional arrays:

function array_multisum (array $arr ): float $sum = array_sum ( $arr );
foreach( $arr as $child ) $sum += is_array ( $child ) ? array_multisum ( $child ) : 0 ;
>
return $sum ;
>
?>

Example:

echo array_multisum ( $data );

Notably the function converts strings to float and ignores strings if they are not convertable:

$a = array( «String» , 2 , 4 , 6 , 8 );
echo «sum(a) keyword»>. array_sum ( $a ) . «\n» ;

$b = array( «12.3456» , 2 , 4 , 6 , 8 );
echo «sum(b) keyword»>. array_sum ( $b ) . «\n» ;
?>

sum(a) = 20
sum(b) = 32.3456

If you have a case where your array has int in strings, it sums them up as if there were only int in the array!
function sum_mix($a)
return array_sum($a);
>
var_dump(sum_mix([9, 3, ‘7’, ‘3’]));
Response will be int(22)

array_sum() doesn’t «ignore strings if they are not convertible», it converts them to zero. array_product() does the same thing, where the difference between «ignoring» and «converting to zero» is much more obvious.

//you can also sum multidimentional arrays like this;

Читайте также:  Python pandas new dataframe

function arraymultisum (array $arr ) $sum = null ;

foreach( $arr as $child ) $sum += is_array ( $child ) ? arraymultisum ( $child ): $child ;
>
return $sum ;
>

echo arraymultisum (array( 1 , 4 , 5 ,[ 1 , 5 , 8 ,[ 4 , 5 , 7 ]]));

array_sum converts strings to integer and array_sum(2,’2′) returns 4.

  • Функции для работы с массивами
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    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):

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    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()

    Функция array_sum() возвращает сумму всех значений в массиве.

    Синтаксис

    Параметр значений

    Технические подробности

    Возврат значения: Возвращает сумму всех значений в массиве
    PHP Версия: 4.0.4+
    PHP Список изменений: Версии PHP до версии 4.2.1 модифицировали сам передаваемый массив и преобразовывали строки в числа (которые часто преобразовывали их в ноль, в зависимости от их значения)

    Еще примеры

    Пример

    Возвращает сумму всех значений в массиве (52.2+13.7+0.9):

    Мы только что запустили
    SchoolsW3 видео

    ВЫБОР ЦВЕТА

    colorpicker

    Сообщить об ошибке

    Если вы хотите сообщить об ошибке или внести предложение, не стесняйтесь отправлять на электронное письмо:

    Ваше предложение:

    Спасибо Вам за то, что помогаете!

    Ваше сообщение было отправлено в SchoolsW3.

    ТОП Учебники
    ТОП Справочники
    ТОП Примеры
    Получить сертификат

    SchoolsW3 оптимизирован для бесплатного обучения, проверки и подготовки знаний. Примеры в редакторе упрощают и улучшают чтение и базовое понимание. Учебники, ссылки, примеры постоянно пересматриваются, чтобы избежать ошибок, но не возможно гарантировать полную правильность всего содержания. Некоторые страницы сайта могут быть не переведены на РУССКИЙ язык, можно отправить страницу как ошибку, так же можете самостоятельно заняться переводом. Используя данный сайт, вы соглашаетесь прочитать и принять Условия к использованию, Cookies и политика конфиденциальности.

    Источник

    PHP Array Sum

    PHP Array Sum

    1. Use the array_sum() Function to Sum the Values of an Array in PHP
    2. Calculate the Sum of All Values of a Multidimensional Array in PHP
    3. 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

    Источник

Оцените статью