Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!