Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda