I want to write a function in PHP that can calculate the sum of the elements of the array. The length of the array is given by the argument of this function.

Tried to write, obviously not that help!

function get_sum($arr = 100) { $sum = 0; for ($i = 0; $i <= $arr[]; $i++) { echo $i; } $sum = $sum + $arr[$i]; echo $sum; } 
  • arr.lenght? not it - des1roer
  • 2
    so there is array_sum() . What else does? - cyadvert
  • Can you explain what you were trying to do in your attempt? - Nick Volynkin
  • Why do I need to pass the length of the array, and not the array itself? There is an array - there is a length. - Sergiks
  • Ready function php.net/manual/ru/function.array-sum.php If you want your implementation, the above examples are Yakovlev Vladimir

4 answers 4

I do not quite understand the essence of your question, but if you want to write a function that counts the sum of the elements of an array that is passed to this function, you need to do this:

 function get_sum($arr) { $sum = 0; foreach($arr as $elem) $sum += $elem; return $sum; } 

Example of function call:

 $values = array(1,2,5,100,-30); echo get_sum($values); //выведет 78 

    The length of the array is given by the argument of this function.

    This phrase seems to me ambiguous. It means that the only argument of f-ii is the array itself, and from it we define its length? Or does the function pass two parameters: the array itself and the number of elements that need to be summed, and this number can be less, equal, or even more than the length of the array, and all these cases need to be processed?

    I am guided by the simplest explanation, only the array itself is transmitted.

     function get_sum($arr) { // убрал значение по умолчанию (=100) // – здесь ожидается массив, а не число $sum = 0; // ок, инициализируем сумму for ($i = 0; $i < count($arr); $i++) { // длина массива: count($arr) // перебираем элементы от 0 и до длина_минус_1: // напр. массив [0,1,2] а длина его 3. Поэтому верхнее значение // $i < 3 $sum = $sum + $arr[$i]; // к общей сумме надо прибавить очередное значение из массива – внутри цикла, а не снаружи } return $sum; // есть смысл, чтобы ф-я возвращала результат, // а что с ним делать дальше - выводить на экран или ещё что // пусть решают там, снаружи ф-ии. } // теперь надо как-то использовать эту функцию: echo "Сумма массива [1,2,3] = "; echo get_sum( array(1,2,3) ); echo PHP_EOL; // символ новой строки 

    Ps and if this is not a learning task, PHP has a built-in function that summarizes all the elements of a given array faster, array_sum() :

     echo "Сумма [1,2,3] = " . array_sum([1,2,3]) . PHP_EOL; 
      1. Write the signature of the method accepting an array of numbers
      2. Declare a variable to sum, the value is 0 .
      3. Walk through the array using a for loop with an index from zero to the length of the array, or foreach
      4. At each iteration, add the i-th element to the sum. After completing the cycle, return the result.

        We consider the sum of the elements of the array $ arr [] from 0 to $ n, where $ n is a function parameter

         function get_sum(array $arr, $n) { $sum = 0; for ($i = 0; $i <= $n; $i++) { $sum += $arr[$i]; } return $sum; 

        }

        $ arr = [2, 4, 5, 6, 4, 5]; $ n = 4;

        echo get_sum ($ arr, $ n); // displays 21 folded elements with indices from 0th to 4th