0

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.

2
  • Did you give up? Commented Mar 24, 2022 at 14:54
  • I didn't give up and I did it luckily. Commented Mar 30, 2022 at 16:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.