3

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.

FLiwanag
  • 31
  • 1
  • 3
  • 1
    What error do you get? – John Conde May 01 '17 at 18:58
  • 1
    Why are you looping over the array? `min()` and `max()` will just return you the value, no need to loop. Also, PHP does not have an `avg()` function, might that be the error you are seeing? – gen_Eric May 01 '17 at 18:59
  • 1
    You don't get to invent functions. There's no such thing as `avg()` so you will need to write it. – miken32 May 01 '17 at 19:01

2 Answers2

7

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);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
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);
freginold
  • 3,946
  • 3
  • 13
  • 28