Sami
Sami

Reputation: 1491

Algorithm to read numbers from a .txt file and print the numbers in a foreach loop in PHP

I have a foreach loop in a PHP code which processes 2000 .txt files from a folder, for example:

    $files = glob('files/*.txt');
foreach($files as $file) {
    $rand = rand(5000,10000); 
    $file_name  = basename($file, ".txt");
    echo $file .$rand. $number. '.txt' ."<br>";
// Number should be read from the number.txt file
}

Assume that there is a number.txt file that $number variable is read from in the above example (each number is in one row, see the below picture). Also, assume that we don’t know whether the total number of rows is greater or smaller than 2000. So my question is how to write an algorithm which satisfies the below conditions:

1. If there are more than 2000 listed numbers in the number.txt file, the code prints any number where none of them is duplicated.

2. If there are less than 2000 numbers in the number.txt file, the code prints all listed numbers at least once where it can print duplicated numbers until the foreach loop ends.

number.txt file

Upvotes: 0

Views: 259

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79004

Should get you started:

$files = glob("files/*.txt");

foreach ($files as $file) {
    $lines = file($file);

    if(count($lines) >= 2000) {
        $lines = array_unique($lines);
    }
    foreach($lines as $number) {
        echo $number;
    }
}

Upvotes: 1

Related Questions