Sum of five values

1

I'm trying to do the sum and I do not know which is the most effective way to add five values that will soon be more the simplest is $Datos[0]["Valor"]+$Datos[1]["Valor"]... but it would be the dirtiest so to speak.

I thought of while or for but I do not know how to put the sum syntax so that I add it directly since it would be $Datos[$i]["Valor"] but it takes the values separately without adding.

I'm using the abrupt $C1 = $Datos[0]["Caida1"]+$Datos[1]["Caida1"]+$Datos[2]["Caida1"]+$Datos[3]["Caida1"]+$Datos[4]["Caida1"]; I tried with for ($i = 0, $j = 0; $i <= 4; $j += $i, print $i, $i++); but I do not know how to put the sum there

    
asked by Vicente 05.11.2018 в 13:16
source

2 answers

1

With a for cycle, you can add:

$suma = 0; // Aquí guardamos la suma
for ($i = 0; $i < count($Datos); $i++) {
    $suma += $Datos[$i]["Caida1"]; // ó $Datos[$i]["Valor"]
    // $suma = $suma + $Datos[$i]["Caida1"]; // Es lo mismo
}

Then the result of the sum would be in $suma .

    
answered by 05.11.2018 / 13:38
source
0

Use the array_sum() method that will ask you for an array of values to add, as you can notice although I do not explicitly use a for or some other loop, the array_sum() method does so since iterates or runs through each of the elements that make up the arrangement; then you can replenish your code as follows

<?php


$numeros = array(
                    $num1 = 90,
                    $num2 = 50,
                    $num3 = 50,
                    $num4 = 40,
                    $num5 = 30
                );


echo array_sum($numeros);
    
answered by 05.11.2018 в 13:31