Sum of a specific range in a PHP array

Asked

Viewed 51 times

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?

  • 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.".

1 answer

3


As in PHP the order of the elements of a associative array is defined by the order in which the elements are inserted into this associative array, implying that it is possible to extract a subarray bounded by two keys with this algorithm:

  • With array_keys() get an indexed array containing all keys of the associative array.
  • With array_search() find the initial and final index of the range you want to add.
  • With array_slice() and a bit of linear Algebra extracts the sub array delimited by the two keys.

Then add the values of this sub array with array_sum().

Note: This algorithm does no validity check type of the searched keys or interval.

<?php

$valor1 = 10;
$valor2 = 12;
$valor3 = 9.5;
$valor4 = 18;
$valor5 = 36.2;
$valor6 = 12;
$valores = array(
  'valor1' => $valor1, 
  'valor2' => $valor2, 
  'valor3' => $valor3, 
  'valor4' => $valor4,                            //Correção: o valor original no exemplo é 'valor4' => $valor2 
  'valor5' => $valor5, 
  'valor6' => $valor6
);

$valorinicial = 'valor2';
$valorfinal = 'valor4';

$keys = array_keys($valores);                   //Obtém o array indexado contendo contendo as chaves de $valores.
$inicial = array_search($valorinicial, $keys);  //Obtém o índice da chave $valorinicial.
$final = array_search($valorfinal, $keys);      //Obtém o índice da chave valorfinal.

//Extrai de $valores um sub array que vai do elemento $inicial até $final - $inicial + 1.
$intervalo = array_slice($valores, $inicial, $final - $inicial + 1); 
   
$total = array_sum($intervalo);                //Soma os valores do sub array $intervalo.

echo $total;                                  //39.5

Test the example on Repli.it

  • Man, very good. Thank you. A real lesson! If you allow a question. What would it look like if I didn’t use the first position in that sum? What if I didn’t use the last position? Would that be it? $initial = array_search($initial value, $Keys) + 1; to ignore the first key $interval = array_slice($values, $initial, $final - $initial); // to ignore the last key

  • Yes, in case you would have open intervals at one of the extremes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.