'PHP - sorting arrays based on a file

i am new at PHP and I need some help with sorting arrays based on a files. My code causes the array to have a separate sort - it sorts the contents of the first file first and then the second file.

$file1=@fopen("first.txt","r");
$file2=@fopen("second.txt","r");
while(!feof($file1) && !feof($file2))
{$tab[]=@fgets($file1);$tab[]=@fgets($file2);}
@fclose($file1);
@fclose($file2);

$opening=@fopen("prime.txt","w");
for($i=0;$i<sizeof($tab);$i++){sort($tab);@fwrite($opening,($tab[$i]."\n"));};

I don't know how to sort an array of two files.



Solution 1:[1]

I'm not sure I see the error in your code, other than you only need to sort once. But you can just read into arrays, merge them and then sort:

$tab = array_merge(file("first.txt"), file("second.txt"));
sort($tab);
file_put_contents("prime.txt", $tab);

If it's still not sorting the way you think it should, then the data is not what you think it is. Maybe all lines in first.txt start with a space or invisible character, but not the lines in second.txt. Or something similar.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1