Jump to content

While loop help?? please!!!


jeaker

Recommended Posts

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>
Link to comment
https://forums.phpfreaks.com/topic/25099-while-loop-help-please/
Share on other sites

try[code]<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>[/code]
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 [url=http://www.php.net/trim]trim()[/url] 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:
[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 = '';
}
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.