Kirk
Kirk

Reputation: 101

How do I increment a variable so it chooses differnet lines from a text files in a While Loop

I have a script im writing. Here is whats happening. There is a while loop. In the while loop is a variable which is constant to X. How do i make X change from line one, line two, etc for each cycle of the while loop and pull X from a .txt file. Everything is in root. Thanks

Upvotes: 0

Views: 129

Answers (3)

AaronLS
AaronLS

Reputation: 38365

//get the lines of the file into an array
$file_array = file($file_name);

//go through the array line by line
foreach ($file_array as $line_number => $line)
{
  //you didn't tell us what you are doing with each line
  //so you will need to change this to your liking
  $X = $line; // Handle the line
}

Edit: Note for very large files this may not be a good approach because this will load the entire file into memory at one time.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

$f = fopen("some.txt", "r");
while (!feof($f) && $some_condition) {
    $x = fgets($f);
    // do something
}
fclose($f);

Would this be sufficient?

Upvotes: 2

AaronLS
AaronLS

Reputation: 38365

Here is the pseudo code captain Kirk:

//we assume current working directory is root
fileHandle = openFile("Read","some.txt");
X = pull("X",fileHandle);

while( X is constant )
{
  XFactor = factor(X);
}

I can refine and improve this with more details about what universe you are from, the programming language you intend to use, and more specifics about what you want to happen.

Upvotes: 1

Related Questions