-2
<?php

//array 
$lessFifty = array();
$moreFifty = array();

//number generation
for ($i = 1; i<=30; $i++) {
    $number = rand(0, 100);

//Sorting <50>      
  if ($number < 50 ) {
      $lessFifty[] = $number;
  } else {
      $moreFifty[] = $number; 
  } 
}

print_r($lessFifty); 
print_r($moreFifty);

//Average
echo "<p> average of values less than fifty: </p>";
    array_sum($lessFifty) / count($lessFifty) ;
echo "<p> average of values greater than fifty: </p>" ;  
    array_sum($moreFifty) / count($moreFifty) ;
?>

This is what I have so far. I'm trying to generate 50 random numbers within the range of 0-100. Then I have to sort it into less than or greater than 50.

I also have to calculate the average, range, and median.

When I try to do up to the average, and put it into my browser (with a server enabled), I get a blank page. No errors, just a blank. I've also used PHP Sandbox to test it and get no syntax errors, just a blank results box.

How can I fix this so that the calculations actually occur and show on the page?

Kari
  • 115
  • 1
  • 1
  • 10

2 Answers2

0

2 fixes $ missing from i<=30; and the output of the results echo

<?php


//array 
$lessFifty = array();
$moreFifty = array();

//number generation
for ($i = 1; $i<=30; $i++) {
    $number = rand(0, 100);

//Sorting <50>      
  if ($number < 50 ) {
      $lessFifty[] = $number;
  } else {
      $moreFifty[] = $number; 
  } 
}

print_r($lessFifty); 
print_r($moreFifty);

//Average
echo "<p> average of values less than fifty: </p>";
echo    array_sum($lessFifty) / count($lessFifty) ;
echo "<p> average of values greater than fifty: </p>" ;  
echo    array_sum($moreFifty) / count($moreFifty) ;

Alternative display code:

echo "<p> average of values less than fifty: ".array_sum($lessFifty) / count($lessFifty)."</p>" ;
echo "<p> average of values greater than fifty: ".array_sum($moreFifty) / count($moreFifty)."</p>"
  • Yep, that fixed it. Thanks! – Kari Sep 20 '18 at 21:35
  • i suggest getting a (free) IDE to write code in, it will spot the errors for you. i use https://www.eclipse.org/downloads/packages/release/2018-09/r/eclipse-ide-php-developers –  Sep 20 '18 at 21:36
0

Your script causes an infinite loop and without any error reporting you won't see your script has run out of memory.

You can fix this by fixing your for-loop. You forgot to put a $ before the second i:

for ($i = 1; i<=30; $i++) {
//          ^^^
// it should be
for ($i = 1; $i<=30; $i++) {

To enable error reporting, to see errors (like an out of memory error) in the future you can check How to get useful error messages in PHP? for more information.


However your script will still not print the average values you calculated for that you should add an echo before both of the calculation or you can use concatenation to merge the strings and only use 2 echos.

Tom Udding
  • 2,264
  • 3
  • 20
  • 30