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);
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
print_r($Array);I hope you don't expect it to be written back to the file with that code.