Percentage with PHP with ifs [closed]

0

I get 4 percentages and I do the average dividing by 4. The problem is that sometimes 1 or 2 percentages come with 0 and if I divide by 4 it will not give the right result.

How can I do this? I have difficulty thinking something logical. I've done this by now and it works if all 4 are populated.

    <?php

if(($mediaQualidade != 0) and ($mediaSupervisores != 0) and ($mediaProcessos != 0) and ($mediaDpp != 0)) {
    $mediaTotal = (($mediaQualidade + $mediaSupervisores + $mediaProcessos + $mediaDpp)/4);
}
?>
    
asked by anonymous 18.10.2018 / 16:26

1 answer

1

Well your question is pretty confusing, but from what I understand the percentages you get may be nil at some point and you do not want that null percentage to go into the calculation, right?

In this case one of the possibilities and you work with arrays:

 //Aqui você monta um array com a variáveis que precisa
 $aux = array ($mediaQualidade ,$mediaSupervisores ,$mediaProcessos,$mediaDpp);
 $valores = array();

 //aqui você procura pelos valores nulos e percorre cada posição do vetor
 for($i=0 ; $i < count($aux);$i++)
 {
   //Nesse IF você pega apenas os valores que não são 0
   if($aux[$i] != 0)
   {
    $valores[$i] = $aux[$i];
   }
 }
 //A partir dai basta você utilizar a função array_sum que vai somar todos os itens do array $valores e dividir por 4
 $mediaTotal = ((array_sum($valores))/4) ;
 echo " Sua média é : $mediaTotal" ; 

Note: If the divider varies according to the number of elements, you simply use count in the following $divisor = count ($valores); scheme and put the variable $divisor instead of /4

link to the documentation of the array_sum operation: link

link because I used the count inside the for: Array generates error "Undefined offset"

    
18.10.2018 / 17:09