Jump to content

Array Troubles


ijustdidit2011

Recommended Posts

Im trying to get the average of these scores for school could some one tell me what im doing wrong?

 

Thanks!

 

 

<?php

//mainline

 

$scores=array("6.7","8.1","5.8","7.0","6.6","6.0","7.6","6.1","7.2","7.0");

$judges=array("America","Germany","France","China","Japan","Russia","Chek Republic","Trinidad","Cuba","Jamaica");

$average=0;

 

 

doCalc($scores, $average);

//end mainline

 

    function doCalc($scores, $average)

{

  $scores[$average] = $scores[$average] / 10;

  $average = $scores[$average];

}

 

 

 

 

print("The scores are:  ");

for($i=0; $i<10; $i++)

{

print("\n\n{$judges[$i]}");

print("\n{$scores[$i]}");

 

}

print("\n\nThe Average score is $average");

?>

Link to comment
https://forums.phpfreaks.com/topic/94063-array-troubles/
Share on other sites

You are not returning any values in your function, so the $scores and $average variables are terminated at the closing } of your function. To prevent this you could pass the parameters like this:

 

function doCalc( &$scores, &$average )

 

This is called passing variables by reference. It means that everything you do to those variables in your function, will stay that way, even when the function is closed.

Link to comment
https://forums.phpfreaks.com/topic/94063-array-troubles/#findComment-481863
Share on other sites

Try this mate.

 

<?php
//mainline

   $scores=array(6.7,8.1,5.8,7.0,6.6,6.0,7.6,6.1,7.2,7.0);
   $judges=array("America","Germany","France","China","Japan","Russia","Chek Republic","Trinidad","Cuba","Jamaica");
   $average=0;   
   
   
   $average=doCalc($scores, $average);
//end mainline
   
    function doCalc($scores, $average)
   {
      $total=0;
      foreach($scores as $score) {
        $total=$total + $score;
      }
      $result=($total / 10);
      return $average;
   }

   


print("The scores are:  ");
for($i=0; $i<10; $i++)
   {   
   print("\n\n{$judges[$i]}");
   print("\n{$scores[$i]}");
   
   }
   print("\n\nThe Average score is $average");
?>

 

Set it to loop through the array and add it all up and then return the average.

 

Regards

Liam

Link to comment
https://forums.phpfreaks.com/topic/94063-array-troubles/#findComment-481866
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.