Novice going in circles.

Hi,
For the last two weeks I have been looking at the PHP websites, other teaching videos, the text PHP 5/MySql and am completely stuck with this problem of a created array, which has been sort, but now I just can’t find any notation explaining how to extract a elements that are below the average. I have done this:

<?php $students = array ('Tony'=>75,'Maria'=>89, 'Ray'=>77, 'Carla'=>46, 'Matthew'=>58, 'Lana'=>99, 'Greg'=>67, 'Ariana'=>89,'Denny'=>29, 'Sulle'=>70); print_r ($students); avgGrade($students); $stuAvg = avgGrade($students); function avgGrade($array){ $sumGrd = 0; foreach($array as $grade){ $sumGrd += $grade; } $averages = $sumGrd/count($array); echo "The average student grade is $averages%.


"; } sort($students); foreach($students as $key => $grade){ echo $grade.'
' ; } ?>

This is where I am stuck. How can I comparison operators to extract a listing of students that are below the average grade?

An if statement with the criteria you are after would be what I would use.

You can save yourself a lot of headaches by studying the various built-in array functions at php.net. I have commented out some that will help you very much.
[php]<?php
$students = array (‘Tony’=>75,‘Maria’=>85, ‘Ray’=>77, ‘Carla’=>41, ‘Matthew’=>59, ‘Lana’=>99, ‘Greg’=>67, ‘Ariana’=>89,‘Denny’=>29, ‘Sulle’=>70);

echo ‘

’;
print_r($students);
echo ‘
’;

asort($students); // http://php.net/manual/en/function.arsort.php

echo ‘

’;
print_r($students);
echo ‘
’;

$sumGrd = array_sum($students); // http://php.net/manual/en/function.array-sum.php
$classSize = count($students);

$averages = $sumGrd / $classSize;

echo 'The average student grade is ’ . $averages . ‘%.


’;

foreach ( $students as $key => $value ) {
if ( $value < $averages ) {
echo 'This person ’ . $key . ’ fell below the class average of ’ . $averages . ‘% with a percent score of ’ . $value .’%
';
}
}[/php]

I apologize if I made a math error, while I’m good at math I’m no wizard. ;D

An in case you are wondering “What happens when my array gets a little more complicated” such as

[php]$school = array ( array( “student” => “John Jones”, “grade” => 99, “date” => “2014-10-31”), array( “student” => “Mary Jane”, “grade” => 39, “date” => “2014-10-31”));[/php]

http://php.net/manual/en/function.uasort.php -> this little function then would come in handy to use.

Sponsor our Newsletter | Privacy Policy | Terms of Service