Gloytos htyqo
Gloytos htyqo

Reputation: 355

foreach loop with 3 variables

i have 3 txt files so in each row they have one sentences and i want to print them

$a = '1.txt';
$b = '2.txt';
$c = '3.txt';

$a1= file($a);
$b1= file($b);
$c1= file($c);

$id=1;

echo ' id: '.$id++. 'lang1: ' . $a1. 'lang2:' . $b1. 'lang3:' . $c1 .'<br>' ; 

so result should be

id: 1 lang1: first row from 1.txt lang2:first row from 2.txt lang3:first row from 3.txt

id: 2 lang1: second row from 1.txt lang2:second row from 2.txt lang3:second row from 3.txt

id: 3 lang1: third row from 1.txt lang2:third row from 2.txt lang3:third row from 3.txt

Upvotes: 1

Views: 83

Answers (4)

man0v
man0v

Reputation: 674

All Should be:

$a = '1.txt';
$b = '2.txt';
$c = '3.txt';

$a1= file($a, 'r');
$b1= file($b, 'r');
$c1= file($c, 'r');

$id=1;

while(($a_line = fgets($a1)) !== false) {
    $b_line = fgets($b1);
    $c_line = fgets($c1);
    echo ' id: '.$id++. 'lang1: ' . $a_line . 'lang2:' . $b_line . 'lang3:' . $c_line .'<br>' ; 
}

You should also close the files:

fclose($a1);
fclose($b1);
fclose($c1);

Also, this will only work if you have the same amount of lines in each file.

Upvotes: 0

Alex Hampu
Alex Hampu

Reputation: 36

An example of how to do it:

$a = 'file1.txt';
$b = 'file2.txt';
$c = 'file3.txt';

$a1 = explode("\r\n", file_get_contents($a));
$b1 = explode("\r\n", file_get_contents($b));
$c1 = explode("\r\n", file_get_contents($c));

for($id = 1; $id <= 3; $id++) {
    $line = $id - 1;
    echo "id: {$id} lang1: {$a1[$line]} lang2 {$b1[$line]} lang3: {$c1[$line]} <br>"; 
}

Upvotes: 1

Graham
Graham

Reputation: 8151

Basically, you need to:

  1. Open the 3 files
  2. Read the first line of each file
  3. Output the the data in the format required
  4. Repeat steps 2 and 3 for the other lines

One option for opening a file: http://php.net/manual/en/function.fopen.php

One option for reading the next line from a file: http://php.net/manual/en/function.fgets.php

fgets will return false when the end of file is reached, so you can base your loop on that.

What have you tried already?

Upvotes: 0

Eydamos
Eydamos

Reputation: 591

$file1 = '1.txt';
$file2 = '2.txt';
$file3 = '3.txt';

$handle1 = fopen($file1, 'rb');
$handle2 = fopen($file2, 'rb');
$handle3 = fopen($file3, 'rb');

$id = 1;

while (($a = fgets($handle1)) && ($b = fgets($handle2)) && ($c = fgets($handle3))) {
    echo 'id: ' . $id++ . 'lang1: ' . $a . 'lang2:' . $b . 'lang3:' . $c .'<br>';
}

fclose($handle1);
fclose($handle2);
fclose($handle3);

This will read line by line from the files and print the result you asked for.

Upvotes: 0

Related Questions