How to find the mean by the number of vectors filled?

Asked

Viewed 231 times

1

I need to calculate the average of a vector, but considering only those that had the fields filled.

For example:

HTML:

<label for="Cmes222">Valor:</label>
<input type="text" id="Cmes222" name="Tmes222"><br>
<label for="Cmes444">Valor:</label>
<input type="text" id="Cmes444" name="Tmes444"><br>
<label for="Cmes666">Valor:</label>
<input type="text" id="Cmes666" name="Tmes666"><br>
<label for="Cmes888">Valor:</label>
<input type="text" id="Cmes888" name="Tmes888"><br>

PHP:

$salbasetar[0] = $_POST ["Tmes222"]; 
$salbasetar[1] = $_POST ["Tmes444"];
$salbasetar[2] = $_POST ["Tmes666"];
$salbasetar[3] = $_POST ["Tmes888"];

$salbasetarm = ($salbasetar[0] + $salbasetar[1] + $salbasetar[2] + $salbasetar[3]) / 4;

So instead of 4, I want to divide by the number of vectors that have been filled out. I’ve done a lot of research, but nothing has worked. I think we should be able to do count or foreach, but I couldn’t do it... someone could give an example?

  • See if this question the help.

  • This might work too, but I found one in this other Soen topic: http://stackoverflow.com/questions/4422889/how-to-count-non-empty-entries-in-php-array Thanks for the tip.

1 answer

1


I found the answer in this question soen.

Basically, what worked was:

$result = count(array_filter($salbasetar));

$salbasetarm = ($salbasetar[0] + $salbasetar[1] + $salbasetar[2] + $salbasetar[3]) / $result;

Browser other questions tagged

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