There are several issues with this code.
I've outlined some of them.
The following code with a string-concat operation after reading each line which is wasteful; if you are going to read in an entire file as a string, use file_get_contents
which is much more efficient. It also changes all newlines to "," so at the end $filestring will contain "1, John, Smith,2, Mary, Gray,3, Tim, Cook" - uhg. (It also doesn't check for the result of fgets
so it could also result in an error.)
$fp = fopen("data.txt", 'r');
$filestring ="";
while(!feof($fp))
{
$temp = fgets ($fp);
$temp = rtrim ($temp, "\r\n");
$filestring= $filestring.$temp.",";
}
The following looks like it was meant to split the line into files, however the usage is very wrong. Refer to str_split
for what it means (it splits on length, not character sequence) - basically, the $students array will be only one element long and contain "1, John, Smith,2, Mary, Gray,3, Tim, Cook", from above.
echo $filestring;
echo "Convert string into array";
$students = str_split ($filestring, strlen ($filestring));
echo var_dump ($students);
The following doesn't work due to errors in the previous code and it makes no sense to update the $students array which is "the [supposed] array of lines from the file". (Using appropriate variable names can help clarify code intent.)
echo "Put each value into array cell";
fclose ($fp); # wut? this should be up top!
foreach ($students as $key=>$value){
$students [$key] = explode (",", $value);
# check here
}
Consider starting as so ..
$lines = array(); # Read each line into an array of lines.
# I'm leaving it as such because this is trivial to convert
# it to a streaming approach as per the final comment.
$fp = fopen("data.txt", 'r');
while(!feof($fp))
{
$line = fgets($fp);
if ($line !== false) {
$lines[] = rtrim($line);
}
}
fclose($fp);
# Then, for each line in $lines, extract the Student data and do something
# with it, such as printing a result if there is a match. If you need an array
# of students, create a $students array.
# Note that you don't need the $lines array at all! But could do something
# per-line inside the reading loop, where it uses the $line variable.