Jump to content


Photo

While loop help?? please!!!


  • Please log in to reply
3 replies to this topic

#1 jeaker

jeaker
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 25 October 2006 - 09:34 PM

Here is my code. I am trying to get the php script to read the file Grades.txt. The file contains a first name a last name 4 or 5 grades the a -1. This goes on until the end of the file where there is a -2, to indicate the end of the file. I believed this code would work and have struggled with it for a couple days. Any help would be appreciated.



<html>
<head>
<title>Mailing Data From a File</title>
</head>
<body>

<?php
$line = file("Grades.txt");

$i = 0;
$num = 0;
$cnt = 0;

while ($line[$i] != -2) {
      $first = $line[$i];
      $i++;
      $last = $line[$i];
      $i++;

while ($line[$i] != -1) {
      $num = $num + $line[$i];
      $cnt++;
      $i++;
      }

}
$num = $num / $cnt;
echo "$last, $first, $num";
$i++;
$cnt = 0;
$i = 0;

?>


</body>
</html>


#2 sasa

sasa
  • Staff Alumni
  • Advanced Member
  • 2,804 posts
  • LocationHrvatska

Posted 25 October 2006 - 09:50 PM

try
<html>
<head>
<title>Mailing Data From a File</title>
</head>
<body>
<?php
$line = file("Grades.txt");
$i = 0;
$num = 0;
$cnt = 0;
while ($line[$i] != -2) {
      $first = $line[$i];
      $i++;
      $last = $line[$i];
      $i++;
   while ($line[$i] != -1) {
         $num = $num + $line[$i];
         $cnt++;
         $i++;
         }
$num = $cnt > 0 ? $num / $cnt : 0;
echo "$last, $first, $num<br />";
$i++;
$cnt = 0;
$num = 0;
}
?>
</body>
</html>


#3 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 25 October 2006 - 09:54 PM

When you use the file() function to read all of the lines, each line read includes the newline character at the end. You should use the trim() function to remove it before using the value. Also, you can take advantage of the fact that when you use "++", PHP increments the value of the variable after it uses the current value. Also you are ending the outer loop too soon.

Try the following code:
<?php
$lines = file("Grades.txt");

$i = 0;
$first = '';
$last = '';
while (trim($lines[$i]) != -2) {
      if ($first == '') $first = trim($lines[$i++]);
      if ($last == '') $last = trim($lines[$i++]);
      $num = 0;
      $cnt = 0;

      while (trim($lines[$i]) != -1) {
         $num += trim($lines[$i++]);
         $cnt++;
         }
     $num = $num / $cnt;
     echo "$last, $first, $num<br>";
     $first = '';
     $last = '';
}
?>

Ken

#4 jeaker

jeaker
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 25 October 2006 - 10:00 PM

Thank you both so very much for the help. I know it was a simple script but that had me stumped for the longest time.
Thanks again!!! ;D




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users