jeaker Posted October 25, 2006 Share Posted October 25, 2006 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> Quote Link to comment Share on other sites More sharing options...
sasa Posted October 25, 2006 Share Posted October 25, 2006 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] Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted October 25, 2006 Share Posted October 25, 2006 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 Quote Link to comment Share on other sites More sharing options...
jeaker Posted October 25, 2006 Author Share Posted October 25, 2006 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.