0

I'm trying to sort an array reading it from a file. My code executes but the array in the file does not get sorted. any ideas what am I missing ?

$file = fopen("text.txt", "at");

$Array = file("text.txt");

rsort($Array);

fclose($file);
2
  • Hi, do you want to sort array in descending order? Commented May 1, 2017 at 21:34
  • How do you know? print_r($Array); I hope you don't expect it to be written back to the file with that code. Commented May 1, 2017 at 21:36

1 Answer 1

2

The code above will sort $Array in memory, but will not write the sorted array back to the file. This will write the sorted output back.

file_put_contents("text.txt", $Array)

Here is modified code that (with print_r statements to illustrate the sort):

<?php
$Array = file("text.txt");
print_r($Array);
rsort($Array);
print_r($Array);
file_put_contents("text.txt", $Array);

Note that rsort will sort descending order. That code will sort the following file:

Z
D
A
C

to:

Z
D
C
A
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. You are write a was only sorting the array in memory but not making the changes on the actual file. Thank you again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.