0

Thanks in advance for helping me in this issue,

I have two files

file1.txt which contains:

adam
william
Joseph
Hind 
Raya 

and file2.txt which contains:

Student
Teacher

What I want is to combine the two files in one file in this way, so that when the eof of file2.txt is reached, it re-reads it again and continue the

Combined.txt:

adam
Student
william
Teacher
Joseph
Student
Hind 
Teacher
Raya 
Student
Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
Zufy
  • 65
  • 6

1 Answers1

2

You can achieve this by looping the first text file's lines and inserting the alternate lines from text file #2 using a modulus on the key. The calculation is list #2 key = the remainder of list #1 key divided by the number of lines in list #2, i.e. $list2Key = $list1Key % $numberOfLinesInList2. More info on the modulus operator here.

$f1 = file('1.txt');
$f2 = file('2.txt');

$number_of_inserts = count($f2);

$output = array();
foreach ($f1 as $key => $line) {
    $output[] = $line;
    $output[] = $f2[$key % $number_of_inserts];
}

print_r($output);

This will work with any number of rows in the second text file.

scrowler
  • 24,273
  • 9
  • 60
  • 92