Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Foreach loop and average in PHP

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>";
}

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...