4

I'm rather new to programming in general. I'm starting off with some exercises but I'm kind of getting stuck. I created an array and looped thru with a foreach loop to print out each individual number stored in the array, but I dont know what to do to find the average of the numbers and print it out.

<?php

$myArray = array(87,75,93,95);

foreach($myArray as $value){
    echo "$value <br>";
}

?>
1

2 Answers 2

7

only as an exercise, becuse if you actully wanted to do this you would use @kittykittybangbang's answer

<?php

$myArray = array(87,75,93,95);
$sum='';//create our variable 
foreach($myArray as $value){
    $sum+=$value; //adds $value to $sum
    //echo "$value <br>";
}
echo $sum;
?>

for the count count($myArray); makes the most senses but you could do that in the loop as well:

<?php

$myArray = array(87,75,93,95);
$sum= $count=0;// initiate interger variables
foreach($myArray as $value){
    $sum+=$value; //adds $value to $sum
   $count++; //add 1 on every loop 
   }
echo $sum;
echo $count;

//the basic math for any average:

echo $sum/$count; 
?>

if you don't create $sum and $count before the loop you would get notices returned from php, as the first time it tried to add to either, there would be noting to add to

Sign up to request clarification or add additional context in comments.

2 Comments

Can i ask why $count=0, and $sum=''? :) $sum=0; makes more sense in this case (even if this works, of course)
Only as an exercise to help new programmer fella, we don't initiate variables meant to hold integers as strings :)
6

You could:

$avg = array_sum($myArray) / count($myArray);
echo $avg;

Where:

  • array_sum calculates the sum of all elements in the given array.
  • count outputs the total number of elements in the given array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.