1
I am studying arrays and I can’t go any further in this case. I must sum up all the values of each key, between a specific interval.
Example 1: between value1 and Valor3. Expected result is: 31.5 Example 2: between'value4' and'value6'. The expected result is: 66.2
The code that defines the value that goes in the keys and the mounted array is this:
$valor1 = 10; $valor2 = 12; $valor3 = 9.5; $valor4 = 18; $valor5 = 36.2; $valor6 = 12; $valores = array('valor1' => $valor1, 'valor2' => $valor2, 'valor3' => $valor3, 'valor4' => $valor2, 'valor5' => $valor5, 'valor6' => $valor6);
I have already managed to define through the code below, which will be the interval that should be made the sum.
$valorinicial = 'valor2'; $valorfinal = 'valor4'; $posicaoinicial = array_flip(array_keys($valores))[$valorinicial]; $posicaofinal = array_flip(array_keys($valores))[$valorfinal];
I made some attempts, the last was this (unsuccessful):
$soma = 0;
foreach ($valores as $chave => $valor) {
if ($chave >= $posicaoinicial && $chave <= $posicaofinal) {
$soma += $valor;
}
}
echo $soma;
Is there a reason you are using associative array instead of indexed array?
– Andre
Yes, the association defines the sequence and the logic of the exercise. These values (value1, value2, Valor3) sort the array. I will have to apply in a practical situation that is as follows: "A train has 6 wagons, each transports a different amount of people. Sum the total number of persons in a wagon range. Ex: between wagon 2 and wagon 4.".
– Deyvid Henrique Pereira