Filling an array with data from loop

Hi ,I’ve recently started learning PHP
I am suppose to generate 4 test marks, find the average and then put that average into an array.
This is to be done for 5 students so I’ll have 5 elements in my array.
I need to display that array and the lowest value in the array.

I am unsure how to go about putting the values into the array and displaying it.
I have searched for the problem but can’t find a simple solution.

Thanks for any help.
This is my code so far.

[php]<?php

$avg=array();
$avg[] = 5;
$Average;

function Marks()
{
$T1 = rand(0,100);
$T2 = rand(0,100);
$T3 = rand(0,100);
$T4 = rand(0,100);

echo "

Test one = $T1

";
echo "

Test two = $T2

";
echo "

Test three = $T3

";
echo "

Test four = $T4

";

$Average= (($T1 + $T2 + $T3 + $T4)/4) ;
echo "

Average mark is = $Average

";
echo "

-----------------------------

";

$avg[$intCount] = $Average;

}

for($intCount = 0; $intCount <= 4; $intCount++)
{
Marks();
}

print_r($avg);

?>[/php]

$avg[] = 5; doesn’t tell it that the array should have 5 elements, it says to store the 5 in the first slot, so if you do print_r($avg);. you’ll get array([0] => 5). I tried to use Mars() in a for loop, it didn’t like it at all, its not set up to run in an array. that’s why I moved the array inside the function.

Here you go, tested to make sure it worked.
[php]<?php
$min = array();
function Marks() {
//sets up a loop to do 5 interations and use for the student # counter
for($i=1; $i < 6; $i++) {
$T1 = rand(0,100);
$T2 = rand(0,100);
$T3 = rand(0,100);
$T4 = rand(0,100);
$Average= ($T1 + $T2 + $T3 + $T4)/4;
$min[] = min($T1, $T2, $T3, $T4); // finds the lowest number out of the bunch

	foreach($min as $val) { // loops through the $min array to display the lowest test score for each student, turns it red
		if($T1 == $val) {
			$T1 = "<span style='color: red'>$val</span>";
		}
		if($T2 == $val) {
			$T2 = "<span style='color: red'>$val</span>";
		}
		if($T3 == $val) {
			$T3 = "<span style='color: red'>$val</span>";
		}
		if($T4 == $val) {
			$T4 = "<span style='color: red'>$val</span>";
		}
	}
	// creates a running tally for the test results
	$ans .= "<p style='font-weight: bold;'>Student $i</p>";
	$ans .= "<p>Test one = $T1<br />";
	$ans .= "Test two = $T2<br />";
	$ans .= "Test three = $T3<br />";
	$ans .= "Test four = $T4<br />";
	$ans .= "Average mark is = $Average<br />";
	$ans .= "----------------------------- </p>";
}
return $ans; // sends it back to the function call.

}
echo Marks();
?>[/php]There you go. I started the loop with 1 so you wouldn’t have a student 0 being displayed. You could always use a separate for loop to do the student counter, but this is good enough for what you want. All of that could be found in tutorials, just need to know what to look for.

It all works, but if I missed something or misunderstood the question, just let me know what needs to change.

Sponsor our Newsletter | Privacy Policy | Terms of Service