Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Finding average value in an array

I am trying to find the minimum, maximum and average value in a number array:

I have the following code below:

$number = array(15,20,100,10,25,30);

for ($i=0; $i<count($number); $i++){
    //Find maximum number by max function.
    if ($number[$i] == max($number)){
        //Print maximum number.
        $max = $number[$i];
    }

    //Find minimum number by min function.
    elseif ($number[$i] == min($number)) {
    //Print minimum  number.
        $min = $number[$i];
    }
    //Find the average 
    else ($number[$i] == avg($number)){
    //Print average number
        $avg =$number[$i];
    }

}

echo "min value is $min <br/>";
echo "max value is $max <br/>";
echo "average value is $avg </br>";

It seems to be giving me a syntax error on the average part. Please kindly help.

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your for loop is counterproductive here. You're already using almost all the built-in functions you need to get the values you want, but with the for loop, you're using them many more times than necessary. All you need is:

$max = max($number);
$min = min($number);
$avg = array_sum($number) / count($number);
about 4 years ago · Santiago Trujillo Relatório

0

In PHP, there's no inherent avg() function, but you can get the average easily. Sum up the total as you loop through:

$total = $total + $number[$i];

then divide by the number of values:

$avg = $total / count($number);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda