I’m trying to create a simple average calculator using an array with randomly generated numbers. I think the code is pretty solid but I’m being returned this error:
Notice: Undefined offset: 10 in ../average/averageresults.php on line 31
Line 31:
for ($i=0; $i<=10; $i++) { echo $array[$i]."<br />"; }
Rest of code is as follows:
<?php
$array = array();
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$i=0;
$sum = array_sum($array);
$count = count($array);
$avg = $sum/$count;
for ($i=0; $i<=10; $i++)
{
echo $array[$i]."<br />";
}
echo "The average of these numbers is: ".$avg;
?>
You’re “off by 1”. The array has 10 elements, 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. There is no 10.
Change your for loop to:
for ($i=0; $i<10; $i++)“less than” instead of “less than or equals to”