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;
array_sum(). What else does? - cyadvert