Percentage with PHP with ifs

Asked

Viewed 61 times

-1

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

How can I do that? I’m having trouble thinking logically. I’ve done this so far and it works if the 4 are filled.

    <?php

if(($mediaQualidade != 0) and ($mediaSupervisores != 0) and ($mediaProcessos != 0) and ($mediaDpp != 0)) {
    $mediaTotal = (($mediaQualidade + $mediaSupervisores + $mediaProcessos + $mediaDpp)/4);
}
?>
  • 1

    And what is your question? What do you want to do? This seems right.

  • 2

    If any comes zeroed you should divide only by 3 or 2? Mathematically speaking, if a value comes zeroed it has no contribution to the total and therefore lowers the average. That is, it makes sense to divide by 4 even if some 0 comes, but obviously it depends a lot on what you’re doing and, for now, only you know it.

  • Ricardo Gonçalves, I don’t know if this is what you want, see an option with B A BA from PHP in this link https://rextester.com/IZTK96971. You can change the values of the variables and click on the button Run it to see the result.

1 answer

1


Well your question is very confusing , but from what I understand the percentages you receive can be null at some point and you do not want this null percentage to enter in 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 just need to use the Count in the following scheme $divisor = count ($valores); and put the variable $divisor in place of /4

link to the documentation of how the array_sum works:http://php.net/manual/en/function.array-sum.php

link to why I used Count inside the for : Array generates error "Undefined offset"

  • PERFECT! THANK YOU!

  • For nothing , if answered you mark this my explanation as answer to the question . Good luck in the development there!

Browser other questions tagged

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