Why your code doesn't work
The function feof()
returns TRUE
if the file pointer is at EOF
or an error occurs. In all other cases, it returns FALSE
. In your code, $array
will always be empty at the beginning, and any code inside foreach
won't get executed. So the file pointer will always be at the beginning of the file (it will never reach the end), meaning feof($handle)
will always return FALSE
.
Essentially, your code translates to:
while (TRUE) {
foreach (array() as $x){
/*
code here will never get executed
*/
}
}
Looks like an infinite loop, right? Your script times out, and PHP then throws that Fatal error.
What can be done to fix it
For what you want to accomplish, a foreach
isn't necessary. You're already using a while
loop, so you don't need to loop through $array
- it's pointless. Simply declare a counter variable ($x
in the code below), and use that to create the array index:
function readFile1($array, $filename){
$handle = fopen($filename, "r");
$numElements = count($array);
$x = 0;
while (!feof($handle)) {
$array[$x] = fgets($handle);
$x++;
}
fclose($handle);
return $array;
}
Note that the $x
variable above is just for demonstration purposes. If you actually wanted to have 0-based array indices, then you could simply push each line to the array using []
syntax or array_push()
. For example:
while (!feof($handle)) {
$array[] = fgets($handle);
}
Now, call the function and store the returned array and use it however you wish:
$arr = readFile1($savedList, "test.txt");
print_r($arr);