Problems with the sum of the values of an array

0

The problem I have is that it does not add the values of several fixes contained in an array, I do not know why here the code:

<?php
    function solution($number) {
    for ($i = 0; $i < $number; $i++) {
                $multiplo = $i * $number;
                $arreglo = [];
                $arreglo[$i] = str_split($multiplo);
                print_r(array_sum(array_column($arreglo, '0')));
            }
        }
    solution('3');
?>
    
asked by JOSE HERRADA 01.10.2018 в 02:52
source

1 answer

2

This is the way to add the elements of the array as you fill in your for, to the left of the equals the elements of the array and to the right its sum. To do this you must start the array where you will store the numbers to add outside the loop, and the sum is made after the loop, which is when you have the array filled. If you start the array within the loop, it will have a single element in each cycle, and the sum of an element is that element, hence the result you had.

I hope that with this you can move forward in your exercise.

    function solution($number) {
       $arreglo = array();
       for ($i = 0; $i < $number; $i++) {
          $arreglo[$i] = $i * $number;
          print_r($arreglo[$i]);
       }
       print_r("=");
       print_r(array_sum($arreglo));
   }
solution('3');
//036=9
    
answered by 01.10.2018 / 14:57
source